Why Functions?

Understand why extracting code into named functions makes programs easier to read and change

quiz.py is getting long. The while loop holds the for loop, the score update, the streak logic, and the grade message — all in one flat block. If you want to change the grade thresholds, you have to hunt through 40 lines to find them.

Functions fix this by giving each piece of logic a name and a place to live.

What a function is

A function is a named block of code. You define it once, then call it by name wherever you need it:

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
greet("Bob")

Hello, Alice!
Hello, Bob!

The def keyword starts the definition. The name comes next, followed by parameters in parentheses. The indented block is the function body.

Parameters and arguments

A parameter is the variable name inside the function definition. An argument is the value you pass when you call it:

def square(n):      # n is the parameter
    print(n * n)

square(5)           # 5 is the argument

Return values

A function can send a result back to the caller using return:

def add(a, b):
    return a + b

result = add(3, 4)
print(result)       # 7

Without return, the function returns None — a special value meaning "nothing."

What you will extract from quiz.py

In this lesson, you will create three functions:

  • ask_question — displays a question, gets the player's answer, prints feedback, and returns whether they were correct
  • show_results — takes a score and total, then prints the score line and grade message
  • run_quiz — runs the for loop and calls show_results

Each function has one clear job. The while True: loop at the bottom shrinks to just run_quiz() and the play-again prompt.

Next Chapter →