Click here to Skip to main content
15,900,110 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have a problem here when I was going to make a text-based adventure game. Here's My Code.
def adventure():
    print("You are in front of the towers' gate. Will you Enter?")
    ch = ""
    while ch.lower() != 'y' or ch.lower() != 'n':
        print("Please Choose")
        ch = input("[Y] or [N]: ")
        print(ch)
    print("You are out of the loop!")


adventure()


For some reason even though I put an input of "y" or "n" the loop still won't break.

What I have tried:

I tried making it take an int instead
def adventure():
    print("You are in front of the towers' gate. Will you Enter?")
    ch = ""
    while ch.lower() != 1 or ch.lower() != 2:
        print("Please Choose")
        ch = input("[1] or [2]: ")
        print(ch)
    print("You are out of the loop!"

adventure()

and as I expected... It still didn't break out of the loop
Posted
Updated 26-Oct-21 3:36am
v2

That is because the test of your while loop is wrong: you wrote 'or' when you should've written 'and'.
Python
while ch.lower() != 'y' and ch.lower() != 'n':

Since a character cannot equal two values at the same time, an or test here yields to always return true.
 
Share this answer
 
You are testing whether the entered character is not equal to Y or not equal to N. So if it is equal to Y it will not be equal to N, and vice versa. You need to test if it is not equal to both characters:
Python
while ch.lower() != 'y' and ch.lower() != 'n':

Now, if it is equal to Y or N it will exit the loop.
 
Share this answer
 
Look at your condition:
Python
while ch.lower() != 'y' or ch.lower() != 'n':

If ch is "y" then it's not "n" - it can't be both.
Similarly, if ch is "n" then it's not "y"
So every time you check, one or other of those tests will be true, so it goes around again.

Try replacing or with and and it'll exit the loop when you enter one or the other.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900