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

26. The Scoreboard Workshop · Turn a Rule into a Function

Pass an argument and use a returned result in the caller.

Lesson files · lessons/functions/parameters-and-return

Before you start
- Define a function with def and call it by name.
- Multiply two numbers to calculate a total.

By the end
- Use a parameter to receive the star count.
- Use return to give the calculated reward back to the caller.
- Explain how the caller uses that result.

Where you can use it
Calculate the cost of a supply order in a function. Return the amount so another part of the program can add it to the bill.

The function reward has a parameter named stars. In the call reward(3), the number 3 is the argument. During that call, stars holds 3.

The return line sends stars * 2 back to the caller. In print(reward(3)), reward(3) produces 6, and then the outer print shows it. You could also store the result with coins = reward(3) and use coins in another calculation.

Predict
What could a caller do with reward(3)?
- Only display it.
- Save or combine the result.

Worked example (example.py)

def reward(stars):
    return stars * 2

print(reward(3))


Example result
6

Make reward(stars) return three coins for each star. Read a star count and print the returned value.

Starter program (starter.py)

def reward(stars):
    return stars * 2

print(reward(3))


Hint
Put the multiplication in the function and the input and print outside.

Case 1. Try the sample
Input
4
Expected output
12

Case 2. Zero stars
Input
0
Expected output
0

Stretch
Add a second parameter for the number of coins to award per star.

Reflect
What would change if you replaced return with print and kept print(reward(...))?

Check your prediction
Save or combine the result. The caller receives the number 6 and can use it like any other number.
