Search code examples
pythonif-statementlowercase

Using .lower or 'or' in if __ is __ statement causes incorrect if statement flow in python 3.6


I searched and couldn't seem to find anyone who has had this same issue, although I'm very new to python and there's a great chance it is just user error.

I'm having problems using both 'or' and .lower in an if statement. If i use the code:

print('press Y to continue or Q to quit')
end = input()
if end is 'y':
    continue
else:
    break

then my code works correctly, although if the user types in a capital Y, the program continues to the else statement, and ends the program. If I use the following code:

print('press Y to continue or Q to quit')
end = input()
end = end.lower()
if end is 'y': #I have also tried end.lower() here, removing the line above
    continue
else:
    break

The program continues to break with any input. If I print 'end' before the if statement, it returns:

<built-in method lower of str object at 0x7fa6b8176f80>

I've also tried replacing is with ==, which gives me the same results. Is there a problem with how I'm phrasing my if is statement?


Solution

  • You have two problems:

    1. You're using end.lower instead of end.lower(). This means that Python will see the method str.lower instead of its result.
    2. You use is instead of ==. This forces Python to check if the two are the same object, i.e., in the same physical space on your computer. == checks if they have the same value. In general, you pretty much always want ==.