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...."
0

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

I've uploaded my whole program to 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!
@LeecollinsCollins: take a look at the string format mini-language, specifically at the floating point number formatting. There is a specific % percent formatting function there.
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...."

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.