-1

Background:

I'm experimenting with while loops and I just made a simple program nested in a while loop.

Code:

while True:
    userinput = input("Is nem jeff? ")
    if userinput == "y" or "yes" or "Y" or "Yes":
        print ("YAY!")
    elif userinput == "n" or "no" or "N" or "No":
        print ("das sad :(")
    else:
        print ("wrong input")
        break

Problem:

My program should be looping until the user types in an invalid input, but instead, it always returns the value nested in the if statement, no matter what I type in. What am I doing wrong?

2 Answers2

4

Your conditionals aren't doing what you think they are.

In Python, a non-zero-length string evaluates to True in a boolean context. The or operator performs a boolean or operation between the lefthand operand and the righthand operand.

So when you write this:

if userinput == "y" or "yes" or "Y" or "Yes":

What you are saying is this:

if (userinput == "y") or True or True or True:

Which will always evaluate to True. You want to write instead:

if userinput == "y" or userinput == "yes" or userinput == "Y" or userinput == "Yes":

Or more simply:

if userinput.lower() in ['y', 'yes']:
larsks
  • 277,717
  • 41
  • 399
  • 399
0

The reason false down to truthsy or falsy in if conditions. based on your initial code block

print('y'=='yes'or'y')
[output] y
print('n'=='yes'or'y')
[output] y

based on the above you can see that regardless of you input, your first if statement would be evaluated as True. rather than doing that, try doing this instead.

while True:
    userinput = input("Is nem jeff? ").lower()
    if userinput in ['yes','y']:
        print ("YAY!")
    elif userinput in ['no','n']:
        print ("das sad :(")
    else:
        print ("wrong input")
        break
Ade_1
  • 1,480
  • 1
  • 6
  • 17