Booleans, comparisons and if

Python · Essentials · 8 min

Branching is the first step from a calculator to a program, and truthiness is used everywhere.

Comparisons (==, !=, <, <=, >, >=) return True or False. They can be chained: 0 <= x < 10 means 0 <= x and x < 10. Combine conditions with the words and, or and not.

An if statement runs its indented block when the condition is true; elif adds more branches and else catches the rest. Only the first matching branch runs.

Every object has a truth value, so you can write if items: instead of if len(items) > 0:. These are falsy: False, None, 0, 0.0, empty strings, and empty containers ([], {}, (), set()). Almost everything else is truthy.

and and or short-circuit and return one of their operands, not necessarily a bool. a or b returns a if it is truthy, otherwise b; that is why name = given or "anonymous" works as a default. a and b returns a if it is falsy, otherwise b, so user and user.name is safe when user might be None.

For a simple choice between two values, the conditional expression reads like English: label = "even" if n % 2 == 0 else "odd".

Use == to compare values and is only to check identity, which in practice means x is None. Two equal strings or numbers may or may not be the same object, so is on them is a bug waiting to happen.

Example

def classify(temp):
    if temp < 0:
        return "freezing"
    elif temp < 18:
        return "cold"
    elif temp <= 25:
        return "pleasant"
    else:
        return "hot"

print(classify(-3), classify(21))   # freezing pleasant
print(0 <= 5 < 10)                  # True

items = []
if not items:
    print("nothing to do")          # nothing to do

name = "" or "anonymous"
print(name)                         # anonymous
n = 7
print("even" if n % 2 == 0 else "odd")  # odd

Remember

  • Empty containers, 0, '' and None are falsy
  • and/or short-circuit and return an operand
  • Use is only for None; use == for values

Watch out for

  • Writing if x == True: or if len(x) > 0: instead of if x:.
  • Using or for defaults when 0 or '' are valid values, since they are falsy too.

Check yourself

  1. What does `[] or "default"` evaluate to?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/tutorial/controlflow.html#if-statements