Many spellings, one meaning
A user may type yes, Yes or YES, and all three mean the same to a person. Python is case-sensitive, so it needs to be told. The way to do it with the tools of this course is to join one complete condition for each spelling with or. If any one of them matches, the whole condition is true. It is tempting to shorten it to answer == "yes" or "Yes", but this does not do what it seems. Python reads "Yes" alone as a second condition, and a text that is not empty counts as true. So the shortened version is true for every answer. You will meet the reason in the next topic. Always write the whole condition for each spelling.
1answer = input("Snack? ") 2if answer == "yes" or answer == "Yes" or answer == "YES": 3 print("Here you are") 4else: 5 print("Maybe later")
Here you are
| Typed | Printed |
|---|---|
| yes | Here you are |
| Yes | Here you are |
| YES | Here you are |
| yEs | Maybe later |
| no | Maybe later |
1answer = input("Snack? ") 2if answer == "yes" or "Yes": 3 print("Here you are") 4else: 5 print("Maybe later")
Here you are
| Version | Condition | Answer maybe gives |
|---|---|---|
| long | answer == "yes" or answer == "Yes" | Maybe later |
| shortcut | answer == "yes" or "Yes" | Here you are (wrong) |
Spelling cards (no computer). Write a quiz answer on a card, for example the word Delta. Make eight answer cards with different spellings: delta, Delta, DELTA, DeLTa, Delt, Delta with an extra space, D and Delta. For each card write True or False for the condition answer == "Delta" or answer == "delta". Which cards are True? How many conditions would you need to add to also accept DELTA? Write the complete condition. If you have a computer or tablet, run the program with three of your spellings.
1colour = input("Colour? ") 2if colour == "blue" or colour == "Blue": 3 print("Accepted") 4else: 5 print("Rejected")