Control flow & functions
Control flow decides which lines run and how many times; functions package logic under a name so you can reuse it. Together they turn a list of statements into an actual program.
Making decisions
cpu = 85
if cpu > 90:
print("critical")
elif cpu > 70:
print("warning")
else:
print("ok")
Python checks each condition from the top and runs only the first block that matches, then skips the rest. Here it prints "warning" and never looks at else. elif and else are optional.
Loops
A for loop runs once for each item in something iterable (a list, a string, a file, a range of numbers). A while loop keeps going as long as a condition stays true, which is right when you don't know in advance how many times, like retrying until a server answers.
for host in ["web-01", "web-02", "db-01"]:
print("checking", host)
for i in range(3): # 0, 1, 2 (stops before 3)
print(i)
attempts = 0
while attempts < 5:
attempts += 1 # without this the loop never ends
if try_connect():
break # leave the loop early
breakexits the loop immediately;continueskips to the next item.range(start, stop, step)produces numbers;range(0, 10, 2)gives 0, 2, 4, 6, 8.passdoes nothing. It's a placeholder where Python needs a statement but you have nothing to write yet.
Functions
A function is a named, reusable block. You define it once with def and call it as often as you like, passing in values (arguments) that fill its parameters.
def disk_status(used, total=100):
"""Return a label for how full a disk is."""
percent = used / total * 100
if percent > 90:
return "full"
return "ok"
disk_status(95) # 'full' (total defaults to 100)
disk_status(40, total=500) # 'ok'
returnsends a value back to whoever called the function and ends it. A function withoutreturngives backNone.printonly shows something on screen; it doesn't give the value back. Mixing these up is a very common beginner bug.- A parameter with
=has a default, which makes it optional. *argscollects any extra positional arguments into a tuple,**kwargscollects extra named ones into a dict:def total(*args): return sum(args).- The string right under
defis a docstring, the function's built-in documentation.
return hands one value back and ends the function. total wasn't passed, so its default was used.Scope: where a variable exists
Variables created inside a function are local: they exist only while that function runs and disappear afterwards. Code inside a function can read variables from outside, but to reassign an outer variable you'd have to declare it global first. Usually it's cleaner to pass values in as arguments and return results.
Tracing a loop by hand
When a loop confuses you, play computer: write down each variable after every step. Here's a loop that adds up response times:
times = [120, 80, 200]
total = 0
for t in times:
total = total + t
print(total) # 400
| Step | t | total after the step |
|---|---|---|
| before the loop | (none) | 0 |
| 1st time round | 120 | 120 |
| 2nd time round | 80 | 200 |
| 3rd time round | 200 | 400 |
Most loops follow one of a few patterns, and recognising them makes code much easier to write:
# count: how many match?
down = 0
for s in statuses:
if s != "up":
down += 1
# find: stop at the first match
first_error = None
for line in lines:
if "ERROR" in line:
first_error = line
break
# collect: build a new list
big = []
for f in files:
if f["size_mb"] > 100:
big.append(f["name"])
Why functions are worth it
The moment you copy and paste a block of code, it's time for a function. Copied code means every fix has to be made twice, and one copy always gets forgotten. A function also gives the logic a name, so the rest of the script reads like a description of what it does:
def is_valid_port(port):
return 1 <= port <= 65535
def parse_address(text):
host, port = text.split(":") # "db-01:5432" -> "db-01", "5432"
return host, int(port) # a function can return several values
host, port = parse_address("db-01:5432")
if not is_valid_port(port):
print("bad port")
Small functions that each do one job, with clear names, are the main difference between a script that's easy to change and one nobody wants to touch.
Try it yourself
Print the numbers 1 to 20, but print
checkinstead of every multiple of 5.Show an answer
for n in range(1, 21): if n % 5 == 0: print("check") else: print(n)Write a function
status(cpu)that returns"critical"above 90,"warning"above 70, and"ok"otherwise.Show an answer
def status(cpu): if cpu > 90: return "critical" if cpu > 70: return "warning" return "ok"Each
returnends the function, so noelifis needed.Use a
whileloop to count down from 5 to 1, then printgo!.Show an answer
n = 5 while n > 0: print(n) n -= 1 print("go!")