0%

More Expressive Functions · practice

Pure Functions and Side Effects

In the previous lesson, the percentage returned a instead of printing it. That choice lets the rest of the program decide whether to display the result, store it, or use it in another calculation.

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 , it returns the same result. It does not print, request input, or change data outside the function. A function with those properties is called a pure function.

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 , writing a file, and sending a network request.

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, program, or future file exporter can reuse the same returned value.

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_report to build_report.

  • Make it return name: score/total instead 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 with unseen values.