Comparisons, if & elif

Choose the right path

Lesson 3 of 20 · 8 min · Module 1: Values & decisions

A program can choose a different result for different inputs. Comparisons produce booleans; conditions turn those booleans into decisions.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Read comparison expressions
  • Order mutually exclusive branches
  • Test boundary values

The idea

Use if for the first condition, elif for another, and else for the remaining case. Python checks these branches in order and runs the first match.

age = 12
if age < 5:
    print("Free")
elif age < 18:
    print("Child ticket")
else:
    print("Adult ticket")

01Think in ranges

The first branch handles ages below five. If Python reaches the second branch, the age is already at least five, so testing age < 18 is enough. The starter uses def to name a reusable function. The age parameter receives its input, and return sends the chosen price back to the caller.

02Use boundaries as test cases

Ages 4 and 5 sit on opposite sides of one boundary. Ages 17 and 18 sit on opposite sides of another. Testing just one typical child age would miss an incorrect boundary.

Your turn

Define ticket_price(age) for nonnegative ages: return 0 below age 5, 5 for ages 5 through 17, and 10 for ages 18 and above.

What the checks look for

  • Young children enter free
  • Child prices include the boundaries
  • Adults pay ten
Try it in the editor →

Take this with you

Clear conditions start with clear ranges and boundary tests.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →