startswith() in Python acting unexpectedly

Question:

I have the following simple Python code that support to ask if a player wants to play the game again or not.

print('Do you want to play again? (yes or no)')
if not input('> '.lower().startswith('y')):
    print('no')
else:
    print('yes')

However, it does not work correctly. When I run it, it prints a "False" out of nowhere. And regardless if I enter "yes" or "no", the outcome is always "yes".

Do you want to play again? (yes or no)
Falseyes
yes

Do you want to play again? (yes or no)
Falseno
yes

But the following code works.

print('Do you want to play again? (yes or no)')
again = input('> '.lower())
print(again)
again = again.startswith('y')
print(again)

results:

Do you want to play again? (yes or no)
> yes
yes
True

Do you want to play again? (yes or no)
> no
no
False
Asked By: Victor Zhang

||

Answers:

Your brackets are in the wrong position. You want to call .lower().startswith('y') on the result of input('> ').

Change this:

if not input('> '.lower().startswith('y')):

to:

if not input('> ').lower().startswith('y'):
Answered By: GordonAitchJay
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.