0

How you would stop a user from breaking the code by entering an incorrect function? For example:

category = raw_input("Please choose the number of the category you which to play with!")

if category == 1:
    print "Thankyou for choosing",category,".The game will commence shortly!"

if category == 2:
    print "Thankyou for choosing",category,".The game will commence shortly!"

if category == 3:
    print "Thankyou for choosing",category,".The game will commence shortly!"

else:
    print "Incorrect input choose again!"

This works but when I put a correct input in the code it still comes up with 'Incorrect input choose again!' How would I go about to solve this?

Jongware
  • 22,200
  • 8
  • 54
  • 100
LordZiggy
  • 17
  • 5
  • 2
    `category = int(raw_input("Please choose the number of the category you which to play with!"))` should do the trick. – ZdaR Jan 11 '16 at 12:32
  • Your current problem is you are comparing a `str` (which is the return type of `raw_input`) to an `int`. But in general, see the duplicate to handle robustly accepting user input for tasks like this. – Cory Kramer Jan 11 '16 at 12:32

1 Answers1

0

The function raw_input returns a string, and you compare it to an int. That is why you are always getting to the else clause of your if statements. You should cast to int like so before comparing:

category = int(raw_input("Please choose the number of the category you which to play with!"))
Idos
  • 15,053
  • 14
  • 60
  • 75