Decomposition
Decomposition means splitting a program into small functions, each with one clear job. One function can call another to do part of its job.
Read Defining Functions and Parameters & Return first.
Decide on the jobs before writing the code
A score-report program has three jobs:
- Work out the total score.
- Decide whether it reaches a target.
- Display the result.
Name the functions total_score, reaches_target and show_report.
A name like part1 does not say what the function does. Pass in the data a
function needs. Return a result when another function needs it.
One function calling another
def show_ready(): print("Ready!")def start_round(): show_ready() print("Begin.")start_round()This prints Ready! and then Begin.. start_round calls show_ready. When
that call finishes, Python carries on with the next line of start_round.
Call a printing helper on its own line. print(show_ready()) would print
Ready! and then None, because the helper returns nothing.
Building on a helper
A caller can use the value a helper returns in a calculation or comparison.
def score(rolls): return sum(rolls)def is_winning(rolls): return score(rolls) >= 100print(score([40, 35, 30]))print(is_winning([40, 35, 30]))This prints 105 and True. is_winning never adds anything up itself. It
asks score to do it.
Use a Boolean helper in a condition
A helper that returns True or False can go straight into an if.
def reaches_target(score): return score >= 10if reaches_target(12): print("Target reached")if reaches_target(8): print("This line does not run")This prints Target reached once. reaches_target(8) returns False, so the
second print is skipped.
See also: Defining Functions, Comparisons and Logical Operators.
Your turn
Complete both functions. total_score(rolls) returns the sum of the rolls. beats_target(rolls, target) calls total_score and returns True only when the total is greater than the target.
60 True False
def total_score(rolls): # add one return line using sum() passdef beats_target(rolls, target): # add one return line comparing total_score(rolls) to target passprint(total_score([10, 20, 30]))print(beats_target([10, 20, 30], 50))print(beats_target([10, 20, 30], 60))Advanced reading
- Helper order and the call stack — where helpers can be defined, and how Python tracks a chain of calls.
- Variable scope — why each function's variables stay inside it.
- Create your own module — move helpers into a separate file and import them.