──────────────────────────────────────

6. Make Code You Can Trust · Separate Decisions from Effects

Write a function that calculates a new result without modifying its input.

Lesson files · lessons/design-and-testing/pure-calculation

Before you start
- Use append() to build a list in a loop.
- Return a value from a function and print it in the caller.

By the end
- Return a new list of integer percentages from given scores and a maximum.
- Use the two printed lists to verify that the original scores were preserved.

Where you can use it
Calculate bonus scores for a what-if report while retaining the original competition scores.

A pure calculation uses its arguments and returns a result. Giving it the same input twice gives the same output. Read [score + bonus for score in scores] as “for each score, put score plus bonus in a new list.” A loop with append does the same thing. In-place changes and file writes are side effects. Keep those in the caller so you can test the calculation by itself.

Predict
What happens to original?
- It becomes [3, 6].
- It keeps its two original values.

Worked example (example.py)

def add_bonus(scores, bonus):
    return [score + bonus for score in scores]

original = [2, 5]
print(add_bonus(original, 1))
print(original)


Example result
[3, 6]
[2, 5]

Make percentage(scores, maximum) return integer percentages. Read maximum and use the scores [2, 5]. Print the new list and then the original.

Starter program (starter.py)

def add_bonus(scores, bonus):
    return [score + bonus for score in scores]

original = [2, 5]
print(add_bonus(original, 1))
print(original)


Hint
Use score * 100 // maximum for each score. The supplied maximum is positive.

Case 1. Try the sample
Input
10
Expected output
[20, 50]
[2, 5]

Case 2. Another denominator
Input
5
Expected output
[40, 100]
[2, 5]

Stretch
Rewrite your list comprehension as a loop and verify the outputs agree.

Reflect
Why should displaying the scores happen outside percentage()?

Check your prediction
It keeps its two original values. The list comprehension creates a new list.
