Lesson 15: Functions: Reusable Blocks


What you'll learn in this lesson


A function is a named block of code

A function is a block of code with a name, written once and run whenever you call that name. You have already used functions all along: print(), len(), str() are all functions that came with Python. Now you will write your own.

Here is the simplest useful one:

def greet():
    print("Hello, coder!")

greet()
greet()

Output:

Hello, coder!
Hello, coder!

Three parts to learn. def says "here begins a function definition." greet is the name you choose for it. The empty brackets () mean this function takes no extra information — yet. The indented block underneath is the function's body, exactly like an if block's body (Lesson 9): the indent is what belongs to the function.

Nothing happens when Python reads the definition. The body runs only when the function is called — greet() — and each call runs the whole body again. That is why the message prints twice: two calls, two runs. Defining is writing the recipe; calling is cooking the meal.


Parameters: values a function receives

Most functions need information to work with. A parameter is a name listed in the definition's brackets; when you call the function, you hand it a value (called an argument) that the parameter holds while the body runs:

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

greet("Mia")
greet("Sam")

Output:

Hello, Mia!
Hello, Sam!

Same function, different results, because the argument changes what name holds each time. A function can take several parameters, separated by commas:

def describe_pet(name, animal):
    print(name + " is a " + animal + ".")

describe_pet("Biscuit", "dog")
describe_pet("Whiskers", "cat")

Output:

Biscuit is a dog.
Whiskers is a cat.

Arguments match parameters in order: the first argument goes to the first parameter, the second to the second. Mix up the order and you get a grammatical but wrong sentence — or an error — so read calls left to right, carefully.


Printing versus returning

So far every function has printed its result. But often you want a function to hand a value back so the rest of the program can use it. That is what return does:

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

total = add(4, 3)
print(total)
print(add(10, 20))

Output:

7
30

return a + b means "the answer of this function is a + b." The caller can store it (total = add(4, 3)) or print it directly (print(add(10, 20))). Contrast that with a printing function: once it prints, the value is gone — displayed, but unusable by the rest of the program.

The rule of thumb: print when a human needs to see something; return when another part of the program needs to use something. Most real functions return. And one more detail: code after a return inside a function never runs, because returning ends the function at once.


Why functions matter

Functions exist for the same reason loops do: write once, use many times. But they add something loops cannot — a name for an idea. Compare these two programs. Without a function:

print("Hello, Mia!")
print("Hello, Sam!")
print("Hello, Alex!")

With one:

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

greet("Mia")
greet("Sam")
greet("Alex")

Same output. But the second version says what it means: greeting is one idea, done three times. When the greeting needs to change — say, to add an exclamation pattern or a second line — you change it in one place, not three. In big programs, that single-change property is what keeps code manageable at all. You will feel it yourself in the next lesson's guessing game, which is built from small functions doing one job each.


Hands-on exercise

  1. Write a function say_hello(name) that prints a greeting, and call it with three different names.
  2. Write a function double(number) that returns twice its argument. Store the result of double(7) in a variable and print it.
  3. Write a function area(width, height) that returns the area of a rectangle, and print the area of a 5 by 3 rectangle.
  4. Explain in one sentence why double should return its answer instead of printing it.

Quick quiz

  1. What is a function, and what is the difference between defining one and calling one?
  2. What is a parameter, and what is an argument?
  3. In describe_pet("Biscuit", "dog"), which argument goes to which parameter?
  4. What is the difference between printing a result and returning one?
  5. Why is changing a greeting easier in the function version than in the repeated-lines version?

Answer key: 1. A named block of code; defining writes it, calling runs it. 2. A parameter is the name in the definition; an argument is the value handed in at the call. 3. "Biscuit" goes to name, "dog" to animal, in order. 4. Printing displays a value for a human; returning hands it back for the program to use. 5. Because the greeting exists in one place — change it once, and every call uses the new version.


Key takeaways

Next lesson: Mini-Project — The Number-Guessing Game.


Slides

Work through the slides with Helio's narration, or download them:

Open the slidesDownload PowerPointDownload PDF

Try it yourself

Run the lesson's example with real Python, right in your browser (Python loads from the internet, so you need to be online).

Open the demo

Practice file

Download lesson15-practice.pyDownload the solution

# Lesson 15: Functions — Reusable Blocks
# WHAT TO DO: A function is a named block of code. def defines it, and
# calling its name runs it. double() should return twice its number,
# but one line is wrong. Fix line 10: change number + 1 to number * 2.
# HINT: return hands the answer back to the program (it does not print
# it). double(7) should give 14, so the program should print 14.
# Run with F5 in IDLE. You are done when the last line prints 14.

def double(number):
    return number + 1  # <-- CHANGE THIS LINE: return twice the number


result = double(7)
print(result)

Save the file as lesson15-practice.py and run it with F5 in IDLE. On a Mac, if F5 does nothing, use Run, then Run Module, from the menu.

Check yourself

Five quick questions on this lesson. Take the Lesson 15 quiz

Want graded quizzes and progress tracking?

Enroll free in the full course — same 17 lessons, with your progress saved. Free, no payment.