Conditions in code: if–else
Be able to write programs that perform different actions depending on whether a condition is met.
Prerequisites
- ARepeat: loopsrequired
Everyday explanation
If it is raining, you take an umbrella; otherwise, you take sunglasses. In programming, this is called a condition. The program chooses which code to run based on whether a statement is true or false.
if points > 10:
print "Passed"
else:
print "Failed"
The condition points > 10 is either true or false. There is no in-between. The computer evaluates the condition and selects the branch that matches the result.
Interactive
Follow the program with different values:
if age < 7:
price = 0
elif age < 18:
price = 50
else:
price = 100
age = 5 → 0. age = 12 → 50. age = 18 → 100. age = 7 → 50 (7 is not less than 7).
Boundary values are often a source of errors. Always test exactly at the boundary to see which branch is selected.
Mastery means
- Write a program with if–else logic that handles different scenarios
- Predict the outcome of a conditional program for specific inputs
Sign in to do the exercises and build your mastery up.
Sources
- Scratch Wiki (CC BY-SA 4.0) — CC BY-SA 4.0
- The Python documentation (PSF licence) — PSF