Understand the idea
A function names a reusable computation. Parameters receive arguments; return sends a result to the caller and exits the function. Separate computing an answer from printing it so callers can compose and test behavior.
Work through an example
answer=largest([4,1,7,2]) stores 7. print(answer) displays it. A function that only prints 7 returns None unless it explicitly returns another value.
Time and space complexity
Function-call overhead is constant in a bounded model; the body determines asymptotic cost.
Why it works
The contract is: accept comparable values; return their maximum or None when empty.
Common mistakes
- Do not confuse print with return.
- A mutable default argument can retain changes across calls.
Chapter lab · Python implementation
Our running task is to find the largest value in a sequence. A program turns a precise input/output contract into small state changes. Read the example from the top, predict each update, and run its assertions. Python examples use ordinary built-in types; statements inside an indented block belong to that block.
This shared lab connects the chapter's topics. Follow the current lesson's worked example first, then trace the complete implementation. Additional algorithms described in topic exercises are variations you can implement independently.
def largest(values):
if not values:
return None
best = values[0]
for value in values[1:]:
if value > best:
best = value
return best
def largest_without_slice(values):
if not values:
return None
best = values[0]
for i in range(1, len(values)):
best = max(best, values[i])
return bestRun and test the lab
Copy the implementation and these assertions into a Python 3 file and run it. An assertion failure means the actual result differs from the expectation. Add the current topic's exercise and boundary tests to deepen your understanding.
assert largest([]) is None
assert largest([-8, -3, -5]) == -3
assert largest_without_slice([4, 1, 7, 2]) == 7
assert largest_without_slice([0]) == 0What happens after return best executes?
Further reading
Original documentation for the implementation details used in this chapter.
Python data structures