1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

if / elif / else

if runs a block only when a condition is True. The block is the indented lines under the colon.

if temp > 30:
    print("Hot!")
elif temp > 15:
    print("Nice")
else:
    print("Cold")

Python checks from the top and runs only the first branch that matches.

Step through with temp = 20: the highlight tests temp > 30 (False), moves to the elif (True), runs print("Nice"), and never visits the else block.

See it run

temp = 12
if temp > 25:
    label = "hot"
elif temp > 10:
    label = "mild"
else:
    label = "cold"
print(label)

Python tests the conditions top to bottom and runs only the first branch that is True. Watch the highlighted line jump.

Practice if / elif / else

Exercise 1

Use score in the editor below. Set grade with if/elif/else: 90+ is "A", 80+ is "B", 70+ is "C", and anything else is "F".

Exercise 2

Set fee for a parcel using if/elif/else: weight up to 1 kg costs 3, up to 5 kg costs 7, otherwise 12. Start with weight = 5.

Exercise 3

A tank alarm uses four bands: below 10 is "critical", 10 through below 25 is "low", 25 through 90 is "normal", above 90 is "overflow". Set status with if/elif/else for level = 25.

Free lesson: use the editor to practice it.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest