Conditions, loops, and pattern matching

3.15.2

Choose a branch, iterate over collections, and stop or skip loop iterations.

On this page

Choose a branch

if checks a condition, elif adds another test, and else handles the remaining case. Python uses indentation to mark the block. For equality use ==; use = when binding a name.

total = 20
if total >= 20:
    print("Free delivery")
else:
    print("Add delivery fee")
A flowchart tests total >= 20. True prints Free delivery and false prints Add delivery fee. Download image
With total set to 20, the True branch runs.
Example output
Free delivery

Iterate with for and while

for visits an iterable’s items. range(start, stop) excludes stop. while repeats while its condition is true. break exits the innermost loop, continue skips to the next iteration, and pass is an empty statement.

for number in range(1, 6):
    if number == 2:
        continue
    if number == 5:
        break
    print(number)
Example output
1
3
4

Match a value or shape

match selects the first case whose pattern matches and whose guard, if any, is true. A bare name in a pattern usually captures the value. Use quoted literals for exact text and _ as the wildcard.

command = ["show", "Coffee"]
match command:
    case ["show", item]:
        print(item)
    case _:
        print("Unknown command")
Example output
Coffee

Official references