Session 5 of 5 · 75 minutes
Functions and the Guessing Game
Package code into reusable functions, then combine everything you have learned into a finished game.
Goals
By the end of this session you can:
- Define a function with parameters and call it
- Return a value from a function
- Use the random module to pick a secret number
- Combine variables, decisions, loops and functions in one program
Words to know
- function
- A named block of code you can run whenever you want.
- parameter
- A variable that a function receives when it is called.
- return
- Sends a value back from a function to the code that called it.
- module
- A file of ready-made Python tools you can import, like random.
The lesson
Step 1: Your own functions
You have already used functions like print() and input(). Now you will write your own. A function is a named block of code that you can run whenever you want.
def say_hello():
print("Hello!")
print("Welcome to Python.")
say_hello()
say_hello()Hello!
Welcome to Python.
Hello!
Welcome to Python.defstarts the definition, followed by a name and().- The lines inside are indented.
- Writing the function does nothing by itself. It runs only when you call it with
say_hello().
Step 2: Parameters
A function becomes more useful when you can give it information. Names inside the parentheses are parameters.
def greet(name):
print("Hello, " + name + "!")
greet("Amara")
greet("Jabari")Hello, Amara!
Hello, Jabari!Step 3: Returning a value
print() shows something to the user. return sends a value back to the code that called the function, so it can be stored or used in math.
def double(n):
return n * 2
result = double(21)
print(result)
print(double(5) + 1)42
11A function can return True or False too, which makes it a perfect helper for if statements:
def is_even(number):
return number % 2 == 0
if is_even(10):
print("10 is even")10 is evenStep 4: Random numbers
Python comes with ready-made toolboxes called modules. To use one, import it. The random module can pick numbers by chance.
import random
roll = random.randint(1, 6)
print("You rolled a", roll)You rolled a 4Your number will be different each time you run it. random.randint(1, 6) includes both 1 and 6.
Step 5: Plan the guessing game
Before coding, plan it in plain language:
- The computer picks a secret number.
- Ask the player for a guess.
- If the guess is too high, say so. If too low, say so.
- Repeat until the guess is right.
- Tell the player how many guesses it took.
Here is a skeleton. Your job in the project is to fill in the gaps.
import random
def get_guess():
return int(input("Your guess: "))
secret = random.randint(1, 100)
tries = 0
while True:
guess = get_guess()
tries += 1
if guess > secret:
print("Too high!")
elif guess < secret:
print("Too low!")
else:
print(f"You got it in {tries} guesses!")
breakYour guess: 50
Too high!
Your guess: 25
Too low!
Your guess: 37
You got it in 3 guesses!Step 6: What you can do now
Look at the skeleton. It uses almost everything from this workshop:
- variables (
secret,tries) - decisions (
if,elif,else) - loops (
while Trueandbreak) - functions (
get_guess) - modules (
random)
You built a real game. Next you can add a play-again option, limit the number of guesses, or make the game smarter about hints. That is how programmers work: start with something small that works, then keep improving it.
Exercise
Build two helper functions
- Write a function
greet(name)that printsHello,followed by the name. - Write a function
is_even(number)that returnsTrueif the number is even andFalseotherwise. - Call
greetfor three different names and testis_evenwith 4 and 7.
Need a hint?
def is_even(number): then return number % 2 == 0.
Small project
Number guessing game
The computer picks a secret number from 1 to 100. The player keeps guessing, and the program says higher or lower until they win.
- Import
randomand picksecret = random.randint(1, 100). - Write a function
get_guess()that asks for a number, converts it to an int and returns it. - Use a
whileloop. Each time, callget_guess(), compare it to the secret, and printToo high!,Too low!orYou got it!. - Count the guesses with a variable and print
It took you N guesses.at the end. - Ask
Play again? (y/n)and start a new game if the answer isy.
Stretch it: Give the player only 7 guesses. If they run out, reveal the secret number.
Quiz
Check your understanding
Pick one answer for each question. Your score appears right in the page; nothing is sent anywhere.
Feedback on this lesson
Teachers and students: tell us what worked and what didn't. We read this to improve the curriculum.
Received
Thank you for the feedback.
The Education team reviews lesson feedback to improve the curriculum.
Preview mode: this form is not connected to a destination yet, so nothing was sent. Set its web address in src/data/config.json.