Why doesn't this simple if/else statement work? Can you spot the issue?

Hi All,

I’ve stared at this simple bit of code for 30 minutes…I have searched tutorials…but this code doesn’t actually work! What on earth am I missing? No matter what I type…Python totally ignores the elif or else options…it just responds with the Yes option.

Thanks so much!

startGame = input("Would you like to start the Game? Y/N: ")

if startGame == “y” or “Y”:
print(“Lets start the game…as nothing else works!”)
elif startGame == “n” or “N”:
print(“You pressed no”)
else:
print(“You chose something else!”)

Your if statement is parsed this way:

if (startGame == "y") or ("Y"):

The first part may or may not be true (depending on the value of startGame). The second part will always be true because strings other than the empty string compare as true. So the entire if is always true.

You could use one of these alternatives:
if startGame == "y" or startGame == "Y":
if startGame.lower() == "y":
if startGame.lower().startswith("y"): #also matches "yes" and friends
if startGame in ["y", "Y"]:

Thanks so much…this is one of the things us beginners certainly find challenging…the ‘minor’ differences…that make 'all 'the difference! Thanks for that .lower tip too…I was aware of the concept…but couldn’t figure out the syntax. Thank you!

… and "you can't be serious" and "yuck" :slight_smile:

If you only want "yes" or a shortened version of "yes", you can turn it around:

if "yes".startswith(startGame.lower()):

This will be true for "y", "Ye", "yES", etc., but not for "yuck", "yes!", or "Why yes, of course I would!". Accepting the latter two possibilities is left as an exercise for the reader :slight_smile:

Thanks Zachary and ‘Bowl of Red’…they are great tips…that ‘starts’ with is a great option to know about…

thank you!