if statements, explained simply
Every day you make small decisions: if it is raining, take an umbrella. Programs make decisions in the same way using the word if.
An if statement asks a yes-or-no question. If the answer is yes (Python calls it True), the indented lines underneath run. If the answer is no (False), Python skips them and carries on.
Questions usually compare things. A double equals sign == asks "are these the same?", while > and < ask "bigger than?" and "smaller than?".
Example: Only eat when hungry
energy = 2
if energy < 5:
print("Time for a snack!")
print("Back to exploring.")Output
Time for a snack!
Back to exploring.Try this
- Change energy to 8. Which line disappears, and why?
- Write an if statement that prints "Happy birthday!" when a variable called month equals your birthday month.
- Swap < for > and predict the output before you run it.
