runtime
16 / 250
lesson 16 Conditional Logic · beginner

Choose with if

if runs the indented lines only when its test is true. The next line at the left still runs.

You'll be able to
  • Write an if whose test is a comparison
  • See that a false test skips only the indented lines
  • Leave the following line at the left edge
The idea

Until now every line ran, every time. Real programs react to their data: warn when stock is low, cap a fee, ship free over a threshold. if asks a question. When the answer is true, Python runs the lines that are indented under it. When the answer is false, it skips those lines.

The if line ends with a colon. The next line that starts at the left edge runs either way. Indenting (four spaces) is how Python knows which lines belong to the if.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · A test that is true
price = 20
if price >= 15:
    print("Ships free")
print("Done")
example-2.py · A test that is false
qty = 0
if qty > 0:
    print("In the box")
print("Done")

An if can also change a value instead of printing. Compute something, then let an if correct it when a rule applies, and print the result once, at the left edge, after the if.

Mistakes to avoid: a missing colon at the end of the if line is a syntax error. Forgetting to indent the line under it is an IndentationError. Indenting the final print by accident moves it inside the if, so it only prints some of the time.

Review
  • if runs its indented lines only when the test is true.
  • A false test skips those lines and nothing else. A line at the left edge runs either way.
  • An if can correct a value, and one print after it shows the result. Next: else and elif for the other cases.

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Choose with if — Conditional Logic · Runtime