4

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...."
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

8

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I've uploaded my whole program to http://temp-share.com/show/f3YguH62n There is a problem with the percentage part at the bottom also, some of you guys will have a right laugh at this. It is designed to show to school pupils as an introduction to programming - something I really need to get a grip of! – Leecollins Collins Feb 26 '13 at 21:42
  • @LeecollinsCollins: take a look at the [string format mini-language](http://docs.python.org/2/library/string.html#format-specification-mini-language), specifically at the floating point number formatting. There is a specific `%` percent formatting function there. – Martijn Pieters Feb 26 '13 at 21:45
2

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...."
Óscar López
  • 232,561
  • 37
  • 312
  • 386