I've stumbled upon a problem I can't explain.
chosen = input()
if chosen == "1" or chosen == "2":
print("Okay")
else:
print("Please choose between 1 or 2.")
If written like that it executes as intended, but the flow felt weird, so I want to continue with else, so I changed the statement to !=
chosen = input()
if chosen != "1" or chosen != "2":
print("Please choose between 1 or 2.")
else:
print("Okay")
That way (to me) it feels natural to continue the code, but now no input returns "Okay".
CodePudding user response:
Ideally, you'd use in
for this, which reads much cleaner
while True:
chosen = input()
if chosen in ["1", "2"]:
print("Okay")
break
else:
print("Please choose between 1 or 2.")
CodePudding user response:
You need to use the and keyword instead of or,
by using or this makes it so that if you answer 1 then it will not print "Okay" due to the fact that it is not 2 which makes the function true, and vice versa for the input equaling 2.
This should work:
chosen = input()
if chosen != "1" and chosen != "2":
print("Please choose between 1 or 2.")
else:
print("Okay")
Note you may benefit from changing the numbers into integers by doing this:
chosen = int(input())
if chosen != 1 and chosen != 2:
print("Please choose between 1 or 2.")
else:
print("Okay")
The int function makes your input into a number, however it will give an error if the user doesn't put in a number.