Functions: Reusable Blocks

 

What you’ll learn in this lesson

  • What a function is, and why programmers wrap code in one
  • How to define a function with def
  • How parameters carry values into a function
  • The difference between printing a result and returning one
  • How to reuse one function many times

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 8): 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, which is built from small functions doing one
job each.


Functions: Reusable Blocks

Python for Absolute Beginners · Lesson 15

What you’ll learn

  • What a function is, and why programmers wrap code in one
  • How to define a function with def
  • How parameters carry values into a function
  • The difference between printing a result and returning one
  • How to reuse one function many times
1 / 14

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()
  • def says “here begins a function definition”; the name follows, then brackets
  • The indented block underneath is the function's body
  • Nothing happens when Python reads the definition — the body runs only when the function is called
2 / 14

Your first function

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

greet()
greet()

Hello, coder!
Hello, coder!

Defining is writing the recipe; calling is cooking the meal. Two calls, two runs.

3 / 14

Parameters: values a function receives

  • A parameter is a name listed in the definition's brackets
  • When you call the function, you hand it a value — called an argument
  • The parameter holds that argument while the body runs
  • A function can take several parameters, separated by commas
  • Arguments match parameters in order: first to first, second to second
4 / 14

Greet with a parameter

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

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

Hello, Mia!
Hello, Sam!

Same function, different results, because the argument changes what name holds each time.

5 / 14

Two parameters

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

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

Biscuit is a dog.
Whiskers is a cat.

Read calls left to right, carefully: mix up the order and you get a wrong sentence.

6 / 14

Printing versus returning

  • So far every function has printed its result — but often you want a function to hand a value back
  • return does that: the caller can store the value or print it directly
  • Contrast: once a printing function prints, the value is gone — displayed, but unusable
  • Rule of thumb: print when a human needs to see something; return when another part of the program needs to use it
  • Code after a return inside a function never runs — returning ends the function at once
7 / 14

Return a value

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

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

7
30

Return means “the answer of this function is a + b.” Most real functions return.

8 / 14

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
  • Greeting becomes one idea, done three times, instead of three repeated lines
  • When the greeting needs to change, you change it in one place, not three
  • In big programs, that single-change property is what keeps code manageable
9 / 14

One idea, done three times

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

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

Hello, Mia!
Hello, Sam!
Hello, Alex!

Same output as three repeated print lines — but the greeting lives in one place.

10 / 14

Hands-on exercise

  • Write a function say_hello(name) that prints a greeting, and call it with three different names
  • Write a function double(number) that returns twice its argument; store double(7) in a variable and print it
  • Write a function area(width, height) that returns a rectangle's area, and print the area of a 5 by 3 rectangle
  • Explain in one sentence why double should return its answer instead of printing it
11 / 14

Key takeaways

  • A function is a named block: def defines it, calling its name runs it.
  • Parameters receive values; arguments are the values handed in, matched in order.
  • print shows a value to a human; return hands it back to the program.
  • Code after return never runs — returning ends the function.
  • Functions name ideas, so one change fixes every use.
12 / 14

Take the quiz

Take the Lesson 15 quiz — 5 quick questions to check what you learned.

13 / 14

Next lesson

Mini-Project: The Number-Guessing Game

14 / 14

Press play on any slide and the lesson plays on by itself from there. You can still click Next or click a slide to move on.

Download the Lesson 15 slides (PowerPoint, with narration)

Download the Lesson 15 slides (PDF)

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.

Lesson 15: Functions: Reusable Blocks

One function, greet, is defined once and called twice. Change the first name and run again — only the first greeting changes, which shows the same block being reused.

Loading Python… this can take a few seconds the first time. Please wait — the Run button will become available when Python is ready.

Try this: Change the name to Alex and press Run again — the first greeting becomes “Hello, Alex!” and the Sam greeting stays the same.

The code that runs



Output

Press Run to see the output here.

Practice file

Save this as lesson15-practice.py and run it with F5 in IDLE.

# 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)

Key takeaways

  • A function is a named block: def defines it, calling its name runs it.
  • Parameters receive values; arguments are the values handed in, matched in order.
  • print shows a value to a human; return hands it back to the program.
  • Code after return never runs — returning ends the function.
  • Functions name ideas, so one change fixes every use.

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


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.