Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limit input to integer only (text crashes PYTHON program) [duplicate]

Tags:

python

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...."
like image 940
Leecollins Collins Avatar asked Dec 27 '22 08:12

Leecollins Collins


2 Answers

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
like image 118
Martijn Pieters Avatar answered Dec 28 '22 23:12

Martijn Pieters


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...."
like image 42
Óscar López Avatar answered Dec 28 '22 21:12

Óscar López