Basic Python If Statements Using "or" - python

I am following a beginner program for learning python. I am struggling to find a better way to use an "if" statement with multiple possibilities. I am writing a basic text based game in which the user is able to choose three different difficulty levels: Easy, Medium, Hard. I am just trying to write code that takes in a 1, 2, or 3 to tell the program which level to run. I want to make sure the user input is one of those options, not "4" or "one".
Here is the relevant code I have written:
selected_level = 0
selected_level = raw_input("\n Please select a level by entering 1, 2, or 3 : ")
print selected_level
if selected_level == 1 or selected_level == 2 or selected_level == 3:
print "Pass"
else:
print "Fail"
break
All I am trying to do right now is test that the "if" statement works. However, no matter what input I enter it will print the input and then print "Fail" which tells me it is never entering the first part of the "if" statement.
I have tried testing this with inputs 1, 2, 3, 4, one, etc and it always skips to the "else" statement. Is there a better way to write an "if" statement with multiple or values?

Your issue is that raw_input returns a string, but the if-statement is comparing to ints.
"1" does not equal 1.
Try checking if selected_level == "1" ... "2"... etc. and it should work.
I would compare to strings instead of casting the input to an int, as that will crash the program if the user types something unexpected.
Also for a more succinct check:
if selected_level in ("1", "2", "3"):
print "Pass"

raw_input returns a string. Try int(raw_input(...))

The reason it keeps skipping down to the if statement is because it is comparing the string that you entered to the numbers 1, 2, etc and not to the string value of 1 and 2. If you want to take the numeric value of the input you could do something like:
selected_level = int(raw_input("\n Please select a level by entering 1, 2, or 3 : "))
This will take the integer value of whatever the user inputs.

raw_input (in Python 2.x) returns a str. so selected_level is a str, not int. You must parse it to int before compare it woth int values
selected_level = 0
selected_level = int(input("\n Please select a level by entering 1, 2, or 3 : "))
print selected_level
if selected_level == 1 or selected_level == 2 or selected_level == 3:
print "Pass"
else:
print "Fail"
break

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.

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.

Python: Loop not exiting with "break"

I have this while loop that is testing to make sure the user inputs either 1, 2, or 3. Once the user inputs 1, 2, or 3, the loop keeps going infinitely, i can't get out of it.
while True:
try:
filterselection = raw_input("Please select a filter (1, 2, or 3): ")
if filterselection == "1" or filterselection == "2" or filterselection == "3":
filterselection = int(filterselection)
break
else:
print "Not a valid number try again!"
except TypeError:
print "Lol, that's not a number try again!"
Don't mix tabs and spaces! Here is what I see when pasting your original code into an editor that displays whitespace characters:
The arrows are tabs and the dots are spaces, it is very important that you don't mix these because if you do the code that you see might not be what the Python interpreter sees.

How do i do a Does not equal multiple numbers?

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

Categories

Resources