A program that runs every line once, top to bottom, cannot do much. Control flow is how Python decides which lines run and how many times: branching on a condition, looping over data, and stopping early when the answer is found. Python's versions of these are short, and they lean on the indentation rules from Basic Syntax instead of braces.
Every condition in Python is evaluated for its truthiness. A condition doesn't have to be a bool: any object can be tested, and Python decides whether it counts as true or false.
These values are falsy, meaning they count as false:
False and None0, 0.0"", [], (), {}, set(), b""Everything else is truthy. The bool() function shows how Python sees a value:
1bool(0) # Return: False
2bool(-1) # Return: True
3bool("") This makes the idiomatic way to check for an empty container short:
1if lines:
2 print("got input")0, "" and None apart, since all three are falsy. When 0 is a valid value, such as a port number or an index, test for None explicitly with if x is None: instead of if not x:.An if statement runs its block only when its condition is truthy. elif (short for "else if") adds more conditions, checked in order, and else runs when none of them matched. Only the first matching branch runs:
1score = 72
2
3if score >= 90:
4 grade = "A"
5elifPython has no switch statement in the C sense; a chain of elif is the usual replacement, along with the match statement below.
The comparison operators are ==, !=, <, <=, > and >=. Unlike most languages, Python lets you chain them, which reads like math:
1x = 5
20 < x < 10 # Return: True, same as 0 < x and x < 10
31 <= x <= 3 # Return: FalseTwo more operators test membership and identity:
in and not in check whether a value is inside a container: "flag" in line, port not in (80, 443). For strings, in searches for a substring.is and is not check whether two names refer to the same object. Use them for None (x is None), and == for everything else.Conditions are combined with the keywords and, or and not; Python doesn't use &&, || or ! for these. Both and and or short-circuit: they stop evaluating as soon as the answer is known. That makes it safe to guard a check that would otherwise fail:
1lst = []
2if lst and lst[0] == "admin": # lst[0] is never evaluated when lst is empty
3 print(and and or also return one of their operands, not necessarily a bool. or returns the first truthy value, which is a common way to supply a default:
name = "" or "anonymous" # name = "anonymous"For a simple choice between two values, the conditional expression fits on one line. It reads as "this if the condition holds, else that":
1n = 7
2parity = "odd" if n % 2 else "even" # parity = "odd"A for loop runs its block once for every item in an iterable: anything that can produce its items one at a time, such as a list, a string, a dictionary, a file or a range. The loop variable takes each item in turn:
1for port in [22, 80, 443]:
2 print("scanning", port)scanning 22
scanning 80
scanning 443Looping over a string gives its characters, and looping over a dictionary gives its keys:
1for ch in "abc":
2 print(ch) # a, then b, then c
3
4user = {"name":To loop a set number of times, use range. range(stop) counts from 0 up to, but not including, stop. range(start, stop) picks the starting point, and range(start, stop, step) sets the increment, which can be negative:
1list(range(5)) # Return: [0, 1, 2, 3, 4]
2list(range(2, 6)) # Return: [2, 3, 4, 5]
The stop value is excluded for the same reason slicing excludes it: range(len(lst)) produces exactly the valid indexes of lst.
If you're coming from C, the natural way to loop over a list is by index:
1names = ["alice", "bob", "carol"]
2for i in range(len(names)):
3This works, but it's rarely the right shape in Python. Loop over the items directly, and when you also need the index, use enumerate, which produces (index, item) pairs:
1for i, name in enumerate(names):
2 print(i, name) # 0 alice, 1 bob, 2 carolenumerate(names, 1) starts counting at 1 instead, which is handy for line numbers.
To walk two sequences side by side, use zip, which pairs up their items and stops at the end of the shorter one:
1names = ["alice", "bob", "carol"]
2uids = [1000, 1001, 1002]
3for loop over that same list makes the loop skip or repeat items. Loop over a copy (for x in lst[:]:) or build a new list instead.A while loop repeats its block as long as its condition stays truthy. Use it when you don't know in advance how many times to loop, such as repeating until a value converges or until input runs out:
1n = 27
2steps = 0
3while n != 1:
4 n = n // 2If the condition never becomes false, the loop runs forever. Press Ctrl+C to interrupt a script that's stuck.
while True: loops on purpose, with a break inside deciding when to stop. It's the usual shape for reading input until a sentinel value:
1while True:
2 line = input("> ")
3 if line == "quit":
4 breakTwo statements change the flow inside any loop:
break leaves the loop immediately.continue skips the rest of the current pass and moves on to the next item.1for n in range(10):
2 if n % 2 == 0:
3 continue Loops in Python can also have an else clause, which runs only if the loop finished without hitting a break. It replaces the "found" flag you would otherwise need when searching:
1for n in [4, 6, 9, 10]:
2 if n % 2 == 1:The else here belongs to the for, not to the if. It's an unusual feature, and plenty of Python programmers avoid it, but you'll see it in other people's code.
The pass statement does nothing at all. Python needs at least one statement in every block, so pass stands in where you have nothing to write yet:
1for line in lines:
2 pass # TODO: parse each linePython 3.10 added the match statement, which compares a value against a series of patterns and runs the first one that fits. In its simplest form it works like C's switch, but without fall-through between cases:
1command = "up"
2
3match command:
4 case "up":
5 y = -The _ pattern matches anything, so it acts as the default case. Several values can share a case with |, as in case "up" | "north":.
Patterns can do more than compare values. They can unpack a sequence and bind its parts to names, which makes match a clean way to handle parsed input with different shapes. Here, each line of input is split into words and matched on its structure:
1def run(line):
2 match line.split():
3 case [case ["forward", n] only matches a list of exactly two items whose first item is "forward", and it binds the second item to n. A case can also carry a guard, an if that must be true as well:
1match point:
2 case (0, 0):
3 print("origin")
4match needs Python 3.10 or newer. On older versions it's a SyntaxError, so stick to if/elif in scripts that have to run on old systems.