0

I have some Python code using raw_input(). I want to automatically go back to the raw_input if the user gives an invalid response. How do I do this?

first code:

name = raw_input("Enter Name: ")

If the user presses Enter without giving a name (which can be anything) how would I go back to raw_input?

second code:

def start():
        answer = raw_input("Go outside (y,n)? ").lower()
        if answer == "y":
                print "I agree! We've only been here for a few days. Let's do some more exploring!"
        elif answer == "yes":
                print "I agree! We've only been here for a few days. Let's do some more exploring!"
        elif answer == "no":
                print ""
                raw_input("I think we should do some more exploring; we've only been on this planet for a few days... (Press 'Enter')")
        elif answer == "n":
                raw_input("I think we should do some more exploring; we've only been on this planet for a few days... (Press 'Enter')")
                print ""
        else:
                print "Press 'y' for yes and 'n' for no"

start()

I'm trying to go back to raw_input if 'else' occurs or if the user responds with "n" or "no"...

Community
  • 1
  • 1
James
  • 11
  • 4

1 Answers1

1

Try a while loop?

name = ''
while not name:
    name = raw_input("Go outside (y,n)? ").rstrip().lower()
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • I don't really understand that; could you go into a bit more depth, please? – James Oct 02 '15 at 21:12
  • @James To do something more than once you need a loop. `while` is one of the types of loops (`for` is another). So you call raw_input(), check to see if the user entered anything. While they haven't, do it again. – dsh Oct 02 '15 at 21:15
  • This is actually wrong, the OP should loop until name is in a set of valid strings, this will break the loop without getting some valid input – Padraic Cunningham Oct 02 '15 at 21:17
  • @PadraicCunningham: The original question asked for empty or not, I agree valid or not would be more correct. Also, @dsh, the `.lower()` you removed was part of the original code, I kept it to have similar behavior (the cost of lowering being almost nil if the string is empty, and needs to be paid regardless if it is not. – ShadowRanger Oct 02 '15 at 21:47
  • Yep, by name not evaluating to False would not mean that the user entered suitable input, just that they did not enter nothing. – Padraic Cunningham Oct 02 '15 at 21:51