Limit input to an integer only (PYTHON text program crashes)

Python's newbie is here trying to limit the quiz entry to only 1.2 or 3.
If the text is entered, the program crashes (because the text input is not recognized)
Here is an adaptation of what I have: Any help is appreciated.

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...." 
+4
source share
2 answers

Use raw_input() instead, then convert to int (intercept ValueError if this conversion fails). You can even enable a range test and explicitly raise ValueError() if this choice is outside the range of acceptable 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 
+8
source

Try this by assuming that choice is a string, as it seems to be 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...." 
+2
source

All Articles