Python novice here, trying to limit quiz input to number 1,2 or 3 only.
If text is typed in, the program crashes (because text input is not recognised)
Here is an adaptation of what I have:
Any help most welcome.
choice = input("Enter Choice 1,2 or 3:")
if choice == 1:
print "Your Choice is 1"
elif choice == 2:
print "Your Choice is 2"
elif choice == 3:
print "Your Choice is 3"
elif choice > 3 or choice < 1:
print "Invalid Option, you needed to type a 1, 2 or 3...."
Use raw_input()
instead, then convert to int
(catching the ValueError
if that conversion fails). You can even include a range test, and explicitly raise ValueError()
if the given choice is outside of the range of permissible values:
try:
choice = int(raw_input("Enter choice 1, 2 or 3:"))
if not (1 <= choice <= 3):
raise ValueError()
except ValueError:
print "Invalid Option, you needed to type a 1, 2 or 3...."
else:
print "Your choice is", choice
Try this, assuming choice
is a string, as it seems to be the case from the problem described in the question:
if int(choice) in (1, 2, 3):
print "Your Choice is " + choice
else:
print "Invalid Option, you needed to type a 1, 2 or 3...."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With