Skip to content

Week 6 of 8

Functions

As programs get bigger, students package code into functions they can name and reuse. They build small helper functions - greet the player, show the score - and call them whenever they are needed, which is exactly how the final game will stay organized.

Estimated time
60 minutes
Project
Game Helper Functions

The idea

A function is a reusable recipe. You write the steps once after def and give it a name; after that, you run all those steps just by calling the name. A parameter lets you hand the function different information each time, so one greet function can welcome any player. Writing a function does not run it; calling it does.

What you will learn

  • Define a function with def and run it by calling its name.
  • Pass information into a function using a parameter.
  • Explain why functions save you from repeating code.
  • Fix a function call that is missing its argument.

New words

function
A named block of code you can run again and again by calling its name.
def
The keyword that creates a new function.
parameter
An input a function takes, listed inside its parentheses.
call
To run a function by writing its name with parentheses, like greet("Alex").

Project: Game Helper Functions

Edit the starter code below and press Run to see it work. Use Reset starter code to go back to the original at any time.

main.py
Terminal

Run your program to see the output.

Expected output

Welcome, Alex!
Score: 0
Score: 10

Mini challenge

Write a new function called game_over() that prints Thanks for playing! and call it at the end of the program.

Debugging challenge

This stops with an error about a missing argument. The greet function asks for a player in its parentheses. Look at the last line - what did the call forget to give it?

Broken code

def greet(player):
    print(f"Welcome, {player}!")

greet()
Show solution
Give the function a value when you call it:
greet("Alex")

Extension challenge

Write a function next_level(level) that prints a line like You reached level 5! using the number you pass in, then call it with a few different levels.

Reflect

You wrote show_score once and used it twice. In your final game, what is something you will do more than once that could become a function?

Teacher notes

Separate two ideas clearly: defining a function does not run it; calling it does. The frequent bug is defining a function with a parameter, then calling it with empty parentheses. Keep each function short and doing one job so the payoff - reuse - is obvious.

Facilitating this lesson? See the teacher & librarian guide for how to run it, common mistakes, and an offline backup activity.

Finished this lesson? Mark it complete to unlock the next week.