0

Hi so I am working on a game and my game at the start asks the user if they want the rules to the game (y/n). I'm using if statements and else for this, so if user puts in y print rules and if user puts in n start game etc...it works fine, until the user puts in an integer or a word or something python doesn't recognize and it just goes and uses the else statement. My game is a math game so I used try statements before that if the user punched in something that's not a number it tells the user "Invalid, try again". The problem I'm having now is how to tell python to try multiple things...

I tried using try x = 'y' or x = 'n' but it says you can't give try multiple operations or something

Please help, Cheers

Drake
  • 19
  • 1
  • 5
  • If you already have working `if` statements, why are you putting in `try`? `try` is used to catch errors, not to compare strings. – interjay Sep 28 '14 at 17:44
  • This is probably a duplicate of either http://stackoverflow.com/q/15112125/3001761 or http://stackoverflow.com/q/23294658/3001761, but it's not clear which! – jonrsharpe Sep 28 '14 at 17:44
  • @interjay because if the user puts in something that isnt y or n it just goes to the else statements, I want to let the user try again if he puts in a different letter or integer – Drake Sep 28 '14 at 17:51

2 Answers2

0

You might want to use the following:

if inp=="Option1":
    ...
elif inp=="Option2":
    ...
elif inp=="Option3":
...
else:
    print "Not known command"
rspencer
  • 2,651
  • 2
  • 21
  • 29
  • How would you let the user try again though, like if they dont put in one of the options its gonna say "not known command" and the game stops working... how would I make it so it asks him for another raw input one that is y or n – Drake Sep 28 '14 at 17:50
  • 1
    See http://stackoverflow.com/questions/23294658/ tl;dr : put it in a `while` loop. – rspencer Sep 28 '14 at 17:51
0

You need a while loop that will keep taking input until the user inputs either y or n

while True:
    inp = raw_input("Add intruction here")
    if inp == "y":
        # code here
    elif inp == "n":
        # code here
    else:
         print "Invalid input"
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • I got it working, just one more problem it gives me invalid input even if I put in y or n. Im using if not statements too, so if not x or y print invalid input try again and then continue or break depending on what they put – Drake Sep 28 '14 at 18:13
  • don't use `if not x or y` what is it supposed to be checking anyway? The code in my answer will work, if you don't enter either y or n then it will ask for input again – Padraic Cunningham Sep 28 '14 at 18:15