Conditions

if, elif, else and the truth value of things.

if runs a block only when the condition is true. The block is marked by indentation, four spaces. In Python indentation is part of the syntax, not decoration: a line without the indent is no longer part of the block.

temperature = 28
if temperature > 25:
    print("Hot")
elif temperature > 10:
    print("Warm")
else:
    print("Cold")

The checks go from top to bottom, and the first matching branch runs. The rest are skipped, even if their conditions are also true.

Comparisons: ==, !=, <, >, <=, >=. They can be chained as in maths: 0 <= age < 18. The logical operators are and, or and not. and and or evaluate the right-hand side only when the answer is not yet clear without it. That is why in items and items[0] > 0 an empty list never gets as far as the index.

Any value can be a condition, not just True or False. These count as false: 0, 0.0, the empty string "", empty collections [], {}, () and None. Everything else is true, including the string "0" and a string of a single space. So if name: is a short way to say "if the name is not empty".

None is checked with is: if result is None:. is checks whether it is the same object, while == checks whether the values are equal. For numbers and strings use ==.

A short choice between two values fits on one line: label = "even" if n % 2 == 0 else "odd".

Practice

  1. Chained comparison

    What does the program print?

    x = 5
    print(1 < x < 10)
    
  2. A true value

    Which of these values counts as true in an if condition?

    • "0"
    • 0
    • ""
    • []
  3. Grade from points

    Write a function grade(score): from 90 points it is "A", from 75 it is "B", from 60 it is "C", otherwise "F". The boundary values get the higher grade.