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!”)
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!
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