1

I have the following code and if the else is triggered, how do I continue to let them input again instead of it exiting the loop?

Tried some while True stuff but couldn't get it to work.

if awaken in ["a", "stand up"]:
    print("Holy...")
elif awaken in ["b", "take a breath"]:
    print("Just more text holding")
elif awaken in ["c", "go back to sleep"]:
    print("")
else:
    print("I don't understand your answer... try again")
Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Matt Jul 15 '19 at 00:34

1 Answers1

1

Put it all inside a while loop.

while True:
    awaken = input("Enter command: ").strip()  # I presume that you are taking input from user
    if awaken in ["a", "stand up"]:
        print("Holy...")
        break
    elif awaken in ["b", "take a breath"]:
        print("Just more text holding")
        break
    elif awaken in ["c", "go back to sleep"]:
        print("")
        break
    else:
        print("I don't understand your answer... try again")

Output:

Enter command: x
I don't understand your answer... try again
Enter command: y
I don't understand your answer... try again
Enter command: a
Holy...

Don't forget to use break.

I'm not sure why yours didn't work initially but the above loop should do the job.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
  • Thanks, is the .strip() necessary? it seems to work without it. I have a if else statement that I want to run before this one but it skips it entirely with the while true loop, how can I work around that? – PixelCardist Jul 15 '19 at 12:11
  • strip() removes any white spaces around the input. I generally put it in whenever working with input(). As far as the other if-else condition is concerned, I need more context. – Bilesh Ganguly Jul 15 '19 at 12:22
  • Good to know. Regarding the rest this is basically the shell of a text based game I'm just practicing with, so it's going to be loaded with if else statements and I just need a way to restart if else statements if they input something that isn't a valid selection. When I added this while True: loop, it skipped the first if else statement I have in this game until this loop was broken and then it ran it but I don't want it to run this first. Would I end up needing to do While True loops for each if/else I do or is there an easier way? – PixelCardist Jul 15 '19 at 12:39
  • I believe I discovered the problem. Indention! I have the whole game wrapped in a main() function, so I didn't have the while True loop indented. Once I did that and indented the if else loop again it worked! – PixelCardist Jul 15 '19 at 13:18