How do i do a Does not equal multiple numbers? - python

i'm using python 3.2.3 idle
here's my code:
number = input("please enter 1 or 2")
if number != 1 or 2: #this part is wrong
print("You didn't enter 1 or 2")
my code is incorrect. i want to make it so that if the user doesn't enter 1 or 2, error pops up. say they enter 1.5, 3, etc or something that isn't 1.0 or 2.0.
how do i do that using the != command?

The problem is that the code is parsed as
if ((number != 1) or 2):
and 2, being nonzero, is always True.
Instead I would suggest
if number not in (1, 2):

You can always use in/not in:
if number not in (1,2):
Don't forget to create an integer out of your number as well...
number = int(input("please enter 1 or 2"))
Your code as is will never give a True result since you're comparing strings to integers (which will always be inequal).

You can try this:
if number!=1 and number!=2

Related

If function error. Not equals to function not working

I am writing this program and it works fine,
I leave it for sometime and the code stops working.
Please help me in this function;
Here is the code:
acceptables = [1, 2, 3, 4, 5, 6, 10]
try :
toss = input("Toss a number from 1 to 6 (10 included): ")
except ValueError:
print("Invalid")
if toss != acceptables:
print("Illegal Numbers!")
time.sleep(2)
exit()
else:
pass
So what should happen is, the user will enter a number in toss and it will check
if the number is from acceptables, if not it will quit the program.
But now, I entered number that is in acceptables and it still ends up showing
"Illegal Number" and quits the program.
Is this a new python3 update or something that I missed out on? Please help
You've got two problems:
toss = input(...) returns a string, but you want to compare that value to ints. Try a type conversion: toss = int(toss) to transform your str from "1" to 1.
You're checking if the number is in the list using if toss != acceptables: which will always be False because an int (or str at the moment) will never be equal to a list. You want to check if toss is in the list of acceptables. Try this instead: if toss in acceptables:
There are a few issues. First, this line:
toss = input("Toss a number from 1 to 6 (10 included): ")
will store the string value of whatever you submit into toss. You likely want this line to read:
toss = int(input("Toss a number from 1 to 6 (10 included): "))
to ensure you get an integer or a ValueError in the case the user types a non-integer string.
Secondly, this line:
if toss != acceptables:
is checking if toss, what would be an int, is not equal to a list, essentially doing this: if 5 != [1, 2, 3, 4, 5, 6, 10]. You instead likely want this to read:
if toss not in acceptables:
To check if this number is in your list of acceptable numbers.

How do I sum numbers from user input in python?(only if they are even numbers)

I am new to programming, and I'm trying to make a code to get six numbers from a user and sum only even numbers but it keeps error like, "unsupported operand type(s) for %: 'list' and 'int' How can I do with it?
Also, I want to make like this,
Enter a value: 1
Is it even number?:no
Enter a value: 2
Is it even number?:yes
Enter a value: 3
Is it even number?:no
Enter a value: 6
Is it even number?:yes
but it keeps like this,
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
Enter a value: 5
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
How can I fix this?
anyone who can fix this problem please let me know
Python 3.7
numbers = [int(input('Enter a value: ')) for i in range(6)]
question = [input('Is it even number?: ') for i in range(6)]
list1 = [] #evens
list2 = [] #odds
if numbers % 2 ==0:
list1.append
else:
list2.append
sum = sum(list1)
print(sum)
And I'd appreciate it if you could let me know if you knew the better code
This should do it. Note that there is no real need to ask the user if the number is even, but if you do want to ask, you can just add question = input('Is it even number?: ').lower() in the loop and then do if question=='yes'. Moreover, note that you cannot perform % on a list; it has to be on a single number.
evens = []
odds = []
for i in range(6):
number = int(input('Enter a value: '))
if number%2==0:
evens.append(number)
else:
odds.append(number)
print(sum(evens))
you are running the first two input statements in for loops and print at the same time.
You can just take inputs first 6 times and store them in a list. After that you can check each input and store in even and odd lists while printing if its even or odd. and print the sum at last.
Your if condition makes no sense:
if numbers % 2 == 0:
What is the value of [1, 2, 3, 6] % 2? There is no such thing as "a list, modulo 2". Modulus is defined between two scalar numbers.
Instead, you have to consider each integer in turn. This is not an operation you get to vectorize; that is a capability of NumPy, once you get that far.
for i in range(6):
num = int(input('Enter a value: '))
# From here, handle the *one* number before you loop back for the next.
If you want to show running sum. You can do something like :
import sys
sum_so_far = 0
while True:
raw_input = input('Enter an integer: ')
try:
input_int = int(raw_input)
if input_int == 0:
sys.exit(0)
elif input_int % 2 == 0:
sum_so_far = sum_so_far + input_int
print("Sum of Even integers is {}. Enter another integer er or 0 to exit".format(sum_so_far))
else:
print("You entered an Odd integer. Enter another integer or 0 to exit")
except ValueError:
print("You entered wrong value. Enter an integer or 0 to exit!!!")

Python operator != isn't working as expected

Does anyone know why this sample is not working? I have not used Python in years and wanted to test NOT operators. As far as I can remember this should work, I have checked online and it appears to be the correct format. Am I missing something?
Essentially it is just asking for an input of 1, 2 or 3. If the user enters those it will break out the loop. If they do not enter either 1, 2 or 3 it will print to screen and loop again. Currently it is only printing "Invalid input!" then looping not breaking.
while True:
x = input("1, 2, or 3?\n")
if x != 1 or x != 2 or x != 3:
print("Invalid input!")
else:
break
I am using Python 3.6.4.
Well, this will be always true. if I type 1, it'll fail the first condition, but it'll pass the other two: x != 2 or x != 3. Any other number different than 1, 2 or 3 will also be true for all the conditions. There's no problem with the comparison operator.
I think you want to do something like:
x = int(input("1, 2, or 3?\n"))
if x not in [1, 2, 3]:
print("Invalid input!")
The conversion of x to int is also important. Otherwise, the comparison of x with the numbers will be always false.

10 Integers and 1 input that is asked too soon in Python 3

I'm trying to create a program right now where the user insert 10 integers, and then gets the possibility to do the following:
program: "What would you like to do?: 1. Show me the biggest integer. 2. Show me the smallest integer. 3. Show me the average of all numbers combined with one decimal. 4. Show me all the entered integers. 5. Terminate this program."
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
s = [max(nr), min(nr), nr, sum(nr)/len(nr)]
z = int((input("What would you like to do? Please enter a number between 1 to 4. ")))
if z == 1:
print(s[0])
elif z== 2:
print(s[0])
elif z == 3:
print(s[0])
elif z == 4:
print(s[0])
else:
print("Please select a number between 1 to 4.")
This is how far I've come, and now I'm just stuck. When I get the "Please enter an Integer" I enter, let's say for example "1". Then I get the "Please enter a number between 1 to 4" directly after that. I would also like the "Please enter a number between 1 to 4" list several options but got: "TypeError: input expected at most 1 arguments, got 5". I also would like a fifth option to terminate the program. I tried "brake" but I guess it doesn't work like that?
I've re-formatted and added some bits to get this example working. Hopefully you can follow everything I've changed from the comments, but feel free to ask.
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
#only calculate params after all numbers are entered (outside for loop)
s = [max(nr), min(nr), nr, sum(nr)/len(nr)]
while 1: #loop forever until user chooses "terminate this program"
#print options in a nicely formatted way
#triple quoted string allows newlines within literal definition (multiline strings)
print("""What would you like to do?:
1. Show me the biggest integer.
2. Show me the smallest integer.
3. Show me the average of all numbers combined with one decimal.
4. Show me all the entered integers.
5. Terminate this program.""")
#we don't specifically need an integer if we're just picking a choice from a list of options
z = input("input: ")
if z == "1": #choices are now strings so be sure to quote them
print(s[0]) #be sure to select proper element from our list 's'
elif z == "2":
print(s[1])
elif z == "3":
print(s[3])
elif z == "4":
print(s[2])
elif z == "5": #now that we are in a separate loop, break will bring us out of it
break
else:
print("Please select a number between 1 to 5.")
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
while True:
s = [max(nr), min(nr), sum(nr)/len(nr), nr]
z = int((input("What would you like to do? Please enter a number between 1 to 4.\n1> Max Value\n2> Min Value\n3> Average\n4> Show All\n5> Terminate\n")))
if (z-1) in range(0,4):
print(s[z-1])
elif z == 5:
break
else:
print("Please select a number between 1 to 4.")
Here is the working version. I will explain each change to get you started on programming Python.
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
s = [max(nr), min(nr), sum(nr)/len(nr), nr]
z = 0
while not 1 <= z <= 5:
z = int((input("What would you like to do? (1) Max ; (2) Min; (3) Avg; (4) All; (5) None. ")))
if z != 5:
print(s[z-1])
Here are the changes I made:
As I originally said in the comments, we shift everything from the s = line to the left, to get it out of the input loop. Remember indentation is syntactically significant.
We swap the 3rd and 4th elements in your s array to conform to the description you had (option 3 is the average, option 4 prints the array)
We set up a while loop to keep asking for a legal option input (1 thru 5). Notice how in Python, you can do things like 1 <= z <= 5. This more natural notation is not something you find in many languages. Notice also how we had to set z = 0. We could have set z = 6 or z = 99 or whatever - basically, any value not between 1 and 5. Without that, z is initialized to the special Python value None - the null value that is nowhere in the set of integers, and will thus fail the 1 <= z <= 5 test.
We modify the message printed to the user just make the options clear
Last but not least, rather than having all the if statements, we take advantage of the fact that the option number is the same as the index in the array of calculations we did. Well, almost the same, except that arrays in Python start at index 0. So, we subtract one from the option number, and that indexes right to the place in the array holding the desired calculation. The only exception is option 5, which is meant to do nothing. So, we still have just one if statement, which tests for that option 5.

How to add and subtract in python

So I am making a statcalc and everything is working except adding. When I select the option to add it just skips it and says select an option. I was wondering what's wrong with it?
numberstoadd = input("What is the first number you want to add? ")
numbertoadd = input("What do you want to add to it? ")
sum = numbertoadd + numberstoadd
print sum
You need to turn your input strings into ints. Like this:
number_1 = int(raw_input("What is the first number you want to add? "))
number_2 = int(raw_input("What do you want to add to it? "))
sum = number_1 + number_2
print sum
In Python 2, input would eval the typed text and return an integer, whereas under Python 3 input just returns a string containing the typed text (equivalent to raw_input in Python 2).
See this link for other changes between Python version 2.x & 3.x
http://docs.python.org/dev/whatsnew/3.0.html
print("Welcome to fizz buzz")
num1=input("Choose a number from 1 to 100")
if num1 is >= 50:
print("hello")
else:
print("good bye")
Sample Input 0
2
1 3
10 100
Sample Output 0
-2
-90
Given a two integers print the difference of two integers.
*Hint: Try to implement without using '-' operator.

Categories

Resources