Learning Hub/Python/Session 5

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.

Python
def say_hello():
    print("Hello!")
    print("Welcome to Python.")

say_hello()
say_hello()
Output
Hello!
Welcome to Python.
Hello!
Welcome to Python.
  • def starts 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.

Python
def greet(name):
    print("Hello, " + name + "!")

greet("Amara")
greet("Jabari")
Output
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.

Python
def double(n):
    return n * 2

result = double(21)
print(result)
print(double(5) + 1)
Output
42
11

A function can return True or False too, which makes it a perfect helper for if statements:

Python
def is_even(number):
    return number % 2 == 0

if is_even(10):
    print("10 is even")
Output
10 is even

Step 4: Random numbers

Python comes with ready-made toolboxes called modules. To use one, import it. The random module can pick numbers by chance.

Python
import random

roll = random.randint(1, 6)
print("You rolled a", roll)
Output
You rolled a 4

Your 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:

  1. The computer picks a secret number.
  2. Ask the player for a guess.
  3. If the guess is too high, say so. If too low, say so.
  4. Repeat until the guess is right.
  5. Tell the player how many guesses it took.

Here is a skeleton. Your job in the project is to fill in the gaps.

Python
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!")
        break
Output
Your 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 True and break)
  • 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

  1. Write a function greet(name) that prints Hello, followed by the name.
  2. Write a function is_even(number) that returns True if the number is even and False otherwise.
  3. Call greet for three different names and test is_even with 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.

  1. Import random and pick secret = random.randint(1, 100).
  2. Write a function get_guess() that asks for a number, converts it to an int and returns it.
  3. Use a while loop. Each time, call get_guess(), compare it to the secret, and print Too high!, Too low! or You got it!.
  4. Count the guesses with a variable and print It took you N guesses. at the end.
  5. Ask Play again? (y/n) and start a new game if the answer is y.

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.

  1. Question 1What does the word def do?
  2. Question 2What does this print?def double(n): return n * 2 print(double(4))
  3. Question 3What is the difference between print() and return inside a function?
  4. Question 4Which line gives a random whole number from 1 to 10, including both ends?
  5. Question 5Why do we put code in a function?