0

I have just started learning Python and I have some issues with the while loop.

instruction_yes_no = ""

while instruction_yes_no.lower() != "y" or "n":
    instruction_yes_no = input("Do you want to see the instruction? Please write 'Y' or 'N'\n")
    if instruction_yes_no.lower() == "y":
        print("You are gonna lose even if you read the instructions...")
        print("\n")
        time.sleep(1)
        instruction()
    elif instruction_yes_no.lower() == "n":
        print("Do you think you are better than me? I will beat you faster since you have not read the instructions")
        time.sleep(1)
    else:
        print("You mortal...you have not chosen a valid input. Type or 'Y' or 'N'")
        time.sleep(1)
    break

Basically I would like to obtain the following:

1) If the user inputs 'y', the instruction() function is called (THIS WORKS)

2) If the user inputs 'n', it prints ""Do you think you are better than me?..." (THIS WORKS)

3) If the user does not type either 'y' or 'n', I would like to keep looping until the user insert or 'y' or 'n'. HOWEVER this is not working.

I am not understanding why. This is how I think it should work:

  • At the beginning the variable instruction_yes_no is set to ""

  • It enter the loop because instruction_yes_no != than 'y' or 'n'

  • Now, instruction_yes_no assumes the value that the user inputs

  • If the user does not input either 'y' or 'n' it should keep looping, but is does not.

martineau
  • 119,623
  • 25
  • 170
  • 301
Magofoco
  • 5,098
  • 6
  • 35
  • 77
  • 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). – martineau Jun 10 '18 at 01:44

2 Answers2

2

If the user does not input either 'y' or 'n' it should keep looping, but is does not

Because you have the break after the if-elif-else. So it will break in any case.

Move that break inside the if block (when instruction_yes_no.lower() == "y").

Messa
  • 24,321
  • 6
  • 68
  • 92
2

Oh, this is a classic common error:

while instruction_yes_no.lower() != "y" or "n":

It's the same as

while (instruction_yes_no.lower() != "y") or True:

You want this instead:

while instruction_yes_no.lower() != "y" and instruction_yes_no.lower() != "n":

Or maybe this, it's shorter :)

while instruction_yes_no.lower() not in ["y", "n"]:
Messa
  • 24,321
  • 6
  • 68
  • 92