1

I am having trouble with this loop, I have been teaching my self for two days now and I'm in a pinch. I have tried googling the answer but it's not helping me with this specific situation.

In Python, I am trying to prompt a user to pick three options and loop the question if one of the options is not selected.

My code is:

power = input("pick a super power: strength, pyrokenisis, or speed---  ")

while power == "strength" or "pyrokenisis" or "speed":

    print("nice")
    break
else:

    print("try again")
halfer
  • 19,824
  • 17
  • 99
  • 186
  • You have to do while True and then add an if statement. – ParthS007 Mar 29 '20 at 18:51
  • Does this answer your question? [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) – Tomerikoo Mar 29 '20 at 18:57
  • Does this answer your question? [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – wwii Mar 29 '20 at 19:18

2 Answers2

2

Put it in a while loop, and add an if statement.

while True:
  power = input("pick a super power: strength, pyrokenisis, or speed---  ")
  if power == "strength" or power == "pyrokenisis" or power == "speed":
    print("nice")
    break
  else:
    print("try again")
    continue
CliffJ
  • 43
  • 7
2

Your logic is just slightly off. You are forgetting to re-prompt and your condition is wrong.

The condition:

power == "strength" or "pyrokenisis" or "speed"

checks if the power variable is equal to strength, or if either of the other two strings are "true". It may help to bracket it:

(power == "strength") or ("pyrokenisis") or ("speed")

Instead, you should be checking with:

power == "strength" or power == "pyrokenisis" or power == "speed"

or maybe use in on a tuple:

power in ("strength", "pyrokenisis", "speed")

So your final code could look something like:

while True:
    power = input("pick a super power: strength, pyrokenisis, or speed---  ")
    if power in ("strength", "pyrokenisis", "speed"):
        print("nice")
        break
    else:
        print("try again")

Notice that I have moved the prompt inside the while loop so that the user can actually try again on each loop. An if statement has also been used to control the program flow.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54