What happens when you call a function and assign the result to a variable? The arguments provide input; the function’s return value provides output. Python evaluates the call, then assigns the returned object to the variable. Every Python function returns a value, even when its definition has no return statement. section 6.2 section 6.2.2
A result you can use
numbers = list(range(5)) sum_numbers = sum(numbers) print(f"Sum of {numbers} is {sum_numbers}") # Sum of [0, 1, 2, 3, 4] is 10 The value returned by sum is assigned to sum_numbers, ready for the print call. section 6.2.1
Do not assume that a method returns the object it changes. list.sort() sorts a list in place but returns None. Thus primes.sort().append(13) fails: append would be called on None, not on the sorted list. Sort first, then append in a separate statement. A function without a return statement likewise returns None implicitly, even if it changes an object passed to it. section 6.2.1 section 6.2.2
Choose an output that makes the function’s purpose clear:
- Return one value for a single result. This is the usual, preferred pattern. section 6.2.2 section 6.2.4
- Return multiple values when they belong together. Python packages them as one tuple; callers can unpack its items into separate variables. section 6.2.2 section 6.6
- Avoid a long collection of results that callers must decipher. Five or more return values may signal that the function is doing too many things. section 6.2.4
Returning two related results
from statistics import mean, stdev def generate_stats(measures): return mean(measures), stdev(measures) average, spread = generate_stats(measures) The two expressions form one returned tuple. Unpacking gives each result a name at the call site. section 6.2.2 section 6.6
Make the output predictable for callers. A return type hint uses -> in the function header: generate_stats(measures: list) -> tuple. A docstring can use :return: to state the result’s type and meaning. These cues help users understand a function without guessing what its call produces. section 6.3.2 section 6.5.3







