Functions
A function is a named, reusable block of code. Functions let you write logic once and use it everywhere, give complicated steps a clear name, and test pieces of your program separately.
Defining and calling
defstarts a function definition, followed by its parameters in brackets.returnsends a value back to whoever called it.- A function without
returnreturnsNone.
Parameters and arguments
Default values
Keyword arguments
Name arguments when you call a function, in any order. This makes calls much easier to read:
⚠️ Never use a mutable value such as
[]as a default:def add(item, items=[])shares one list between all calls. Useitems=None, thenif items is None: items = [].
Any number of arguments: *args and **kwargs
Returning several values
Python functions can return several values at once (as a tuple), which you unpack:
Scope: where variables live
Variables created inside a function are local: they exist only while the function runs.
Pass data in as arguments and get results out with return. Avoid changing global variables from inside functions; it makes programs hard to follow.
Functions are values
You can store functions in variables, pass them to other functions and return them. That's what makes sorted(..., key=...) so powerful:
lambda: small anonymous functions
Use lambda for short, throwaway functions. Anything longer deserves a proper def with a name.
Recursion
A function can call itself. Each call must move towards a base case that stops it:
Writing good functions
- One job per function, with a name that says what it does (
calculate_total,is_valid_email). - Return values rather than printing them, so the caller decides what to do.
- Add a docstring for anything non-obvious.
- Type hints (covered later) document what goes in and out:
def greet(name: str) -> str:
Practice
- Write
is_even(n)that returnsTrueorFalse. - Write
celsius_to_fahrenheit(c)and print a table for 0, 10, 20, 30 and 40 °C. - Write
count_vowels(text)and test it on a few words. - Write
fibonacci(n)that returns a list of the firstnFibonacci numbers.
1.What does a function return if it has no return statement?
2.What does *args collect?
3.Why is def add(item, items=[]) a classic bug?