More Expressive Functions · practice
Pure Functions and Side Effects
In the previous lesson, the percentage
Compare that design with a function whose only job is to print. The difference introduces two useful ideas: calculation and side effects.
This function builds and returns a score line:
def score_line(score, total):
return f"Score: {score}/{total}"
For the same
Now compare it with a function that displays the line immediately:
def show_score(score, total):
print(f"Score: {score}/{total}")
Printing changes the program’s visible output, so it is a side effect. Other side effects include changing a supplied
Side effects are not mistakes. A useful program eventually needs to display, store, or send something. The design choice is whether calculation and action are mixed together or kept in separate places.
Separate building from displaying
Compare these approaches for a topic label:
def show_topic(number, topic):
print(f"{number}. {topic}")
def build_topic_label(number, topic):
return f"{number}. {topic}"
print(build_topic_label(2, "Functions"))
The second design builds the text first and displays it afterward. Because the returned text is an ordinary value, you can store and inspect it:
label = build_topic_label(2, "Functions")
print(label)
print(label == "2. Functions")
The comparison prints True, which confirms that the function returned the expected text. A web page,
Pure functions also reduce surprises. Calling build_topic_label does not silently print.
Which function is pure?
Refactor a reporting function
The starter program mixes building and displaying a report inside one function. Refactor it so build_report only returns the text, while the final print remains outside the function.
Task
Refactor the program.
Rename
show_reporttobuild_report.Make it return
name: score/totalinstead of printing.Do not print inside
build_report.At the bottom, print the
returned by build_report("Mina", 8, 10).
The hidden checks also call the