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

25. The Scoreboard Workshop · Reuse a Goal Chant

Define a function once and run its body more than once.

Lesson files · lessons/functions/define-and-call

Before you start
- Use print() to show a message.
- Use indentation to group steps in a loop.

By the end
- Use def to give a group of instructions a name.
- Use two or more calls to repeat the same function body.
- Trace which lines run when Python reaches each call.

Where you can use it
Give a game one function for its victory message. Call it whenever a player wins so every win gets the same message.

Use def cheer(): to name the function cheer. Its indented body contains the instructions to run each time you call it.

Write cheer() on a line outside the body to call the function. When Python reaches the call, it runs the indented print and then moves to the next instruction after the call. Count the call lines to predict how many chants you will see.

Predict
How many times does the indented print run?
- Twice.
- Three times.

Worked example (example.py)

def cheer():
    print("Go Comets!")

cheer()
cheer()


Example result
Go Comets!
Go Comets!

Change the chant to Go Owls! and call the function three times.

Starter program (starter.py)

def cheer():
    print("Go Comets!")

cheer()
cheer()


Hint
Keep one print in the function. Add a third call outside the indented body.

Case 1. Try the sample
Input
(No input.)
Expected output
Go Owls!
Go Owls!
Go Owls!

Stretch
Make a second function for a celebration after the final call.

Reflect
Where do you edit the chant so every call uses the new words?

Check your prediction
Twice. The two calls execute the body. The definition sets up the function.
