What you’ll get
A size in bytes, in words, the way a file manager shows it:
# sizes.py
def human_size(n):
"""A size in bytes, in words: 4.4 GB, 512.0 KB."""
if n >= 1024 ** 3:
return f"{n / 1024 ** 3:.1f} GB"
if n >= 1024 ** 2:
return f"{n / 1024 ** 2:.1f} MB"
if n >= 1024:
return f"{n / 1024:.1f} KB"
return f"{n} B"
print(human_size(4_700_000_000))
print(human_size(524_288))
print(human_size(812))
print(human_size(1_000_000_000_000))
python sizes.py
# 4.4 GB
# 512.0 KB
# 812 B
# 931.3 GB
Four calls, one piece of logic. It counts in 1024, like Windows, so a 1 TB disk is 931.3 GB again, as in
Numbers. return hands back the answer and leaves the function at once: the next ifs are never reached,
so no elif is needed here.
How it works: def, a call, return
def human_size(n): # def, the name, parameters in parentheses, a colon
"""Description.""" # a docstring: help() and the editor's tooltip show it
... # the body — indented
return result # what to hand back to the caller
def only creates the function — the code inside doesn’t run until it’s called: human_size(812). On the call, the
value 812 goes into the parameter n, the body runs, and return hands the result back to where the call was. That’s
why a call can go anywhere a value fits: in a print, in an f-string, in another calculation.
help(human_size) in interactive mode prints the description from the triple quotes — all of Python’s built-in help
works the same way.
Arguments: by position, by name, by default
def download_time(size_gb, speed_mbit=100):
"""Minutes to download; the default plan is 100 Mbit/s."""
return size_gb * 1000 * 8 / speed_mbit / 60
print(f"{download_time(4.7):.1f}") # 6.3 — the default plan
print(f"{download_time(4.7, 500):.1f}") # 1.3
print(f"{download_time(speed_mbit=50, size_gb=4.7):.1f}") # 12.5 — by name, order doesn't matter
That’s the calculation from Variables and types, now as a function. A parameter with = is optional: if you don’t pass
it, the default is used. Such parameters come after the required ones, otherwise SyntaxError: parameter without a default follows parameter with a default. A call by name is longer but reads without looking at the def.
Yours and theirs: names inside a function
Names a function creates for itself — parameters and anything assigned inside — live only until the call ends and
aren’t visible outside. A function can read names from outside but not change them: an assignment inside creates its
own name, hence the UnboundLocalError under “If it doesn’t work”. So pass data in as arguments and return the result
with return — then the function can be understood entirely from its def line.
Type hints are optional: def area(w: int, h: int) -> int:. Python doesn’t check them — area("3", 4) returns "3333",
repeating the string four times. The editor and the mypy program catch that.
Take it further
uptime_text function: seconds into “14 d 6 h 56 min”The calculation from the “Numbers” chapter goes inside the function, and the answer comes back as an f-string through return.
def uptime_text(seconds):
days = seconds // 86400
hours = seconds % 86400 // 3600
minutes = seconds % 3600 // 60
return f"{days} d {hours} h {minutes} min"
print(uptime_text(1_234_567))
# 14 d 6 h 56 minis_strong function: is the password acceptable — True or FalseThe condition from the “Conditions” chapter can be returned as is: the comparison already gives True or False, no if needed.
def is_strong(password):
return len(password) >= 12 and not password.isdigit()
print(is_strong("123456789012")) # False — all digits
print(is_strong("correct-horse")) # Truehuman_size in decimal units — optionally, via a parameterA binary=True parameter by default; pick the base — 1024 or 1000 — in one line and count from it.
def human_size(n, binary=True):
base = 1024 if binary else 1000
if n >= base ** 3:
return f"{n / base ** 3:.1f} GB"
if n >= base ** 2:
return f"{n / base ** 2:.1f} MB"
if n >= base:
return f"{n / base:.1f} KB"
return f"{n} B"
print(human_size(1_000_000_000_000)) # 931.3 GB
print(human_size(1_000_000_000_000, binary=False)) # 1000.0 GBIf it doesn’t work
NameError: name 'human_size' is not defined
- Cause
- The function was called higher up the file than its
def: Python runs the file top to bottom and doesn’t know about it before thedef. - Fix
- Put all
defs at the top of the file and the calls below.
TypeError: human_size() missing 1 required positional argument: 'n'
- Cause
- Called without an argument, and the parameter has no default value.
- Fix
- Pass a value —
human_size(812)— or give a default in thedef:def download_time(size_gb, speed_mbit=100):.
TypeError: human_size() takes 1 positional argument but 2 were given
- Cause
- More values were passed than the
defhas parameters. - Fix
- Compare the call with the
def; remove the extra or add a parameter.
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
- Cause
- The function computes but doesn’t return: there’s no
return, or aprintin its place. Withoutreturna function givesNone. - Fix
- Make the function’s last line
return result.
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
- Cause
- Inside the function you change a name created outside:
count += 1. The assignment makes the name local, and there’s no local value yet. - Fix
- Pass the value as an argument and return the new one:
count = add(count). There’sglobal count, but that way functions quietly start depending on each other.