Lesson 4 · if and else
Is the milk running low?
- 1. Story
- 2. Guess
- 3. Your turn
KaiYesterday we ran out of milk at four o’clock. Never again.
SitaraLet Python ask a question each morning: is there enough?
Buddy(wags at the word milk)
if asks a question. If the answer is True, the indented lines run. else runs when it is False.
- 1. if checks a question, like milk < 3
- 2. A colon : and 4 spaces mark what is inside
- 3. else runs when the question is False
cafe.py
Try: Change milk to 5, then run it again.
Read · about 1 minute
The basics, in plain words
if asks a question. If the answer is True, the indented lines run. else runs when it is False.
milk = 2
if milk < 3:
print("Order more milk")
else:
print("Milk is fine")- if checks a question, like milk < 3
- A colon : and 4 spaces mark what is inside
- else runs when the question is False
- if / else
- if asks a yes-or-no question. The indented lines run only when the answer is yes; else runs when it is no.
- < > == !=
- Less than, more than, the same as, not the same as.
Common slip: Missing the colon : at the end of the if line, or not indenting the lines under it.
Read all twelve Python basics with Sitara →