1

I've just starting a programming course and im making an adventure game. I've gotten up to this "path" where the user must choose between the market or the blacksmith.

If they choose either they have two choices and if they dont say either choice I want to re-ask and go through the loop again. currently if I type everything in first try it works but if I fail to provide a valid answer it prompts to re-enter then doesn't go through the loop again.

How do I write this to take my:

else:
    print ("Choice must be (Sword / Platemail)...")
    answer = input ("").lower().strip()

and

else:
    print ("Choice must be (Bread / Cabbage)...")
    answer = input("").lower().strip()

return to the top of the loop with the "answer" in order to have the if and elif statments do what they need to do?

Any help recommendations would be amazing please keep in mind im brand new to programming.

Picture of code in question

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 3
    Please don't paste code as a picture. Copy it and paste it and format it using the `{}` button in the editor. We like to replicate on our own machines to get the answer for you, but no one wants to transcribe text out of a picture. – JNevill Feb 23 '22 at 22:14
  • [Please do not upload images of code/data/errors when asking a question.](http://meta.stackoverflow.com/q/285551) – martineau Feb 23 '22 at 23:22
  • Suggest you look at [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) which sounds very similar. – martineau Feb 23 '22 at 23:25

1 Answers1

2

The pattern is like this:

while True:
    answer = input("Choice?").lower().strip()
    if answer in ('sword','platemail'):
        break
    print("Choice must be Sword or Platemail")

For cleaner code, you might want to put this into a function, where you pass the possible answers and return the validated one.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30