defA 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.
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 whatname 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.
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.
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.
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)
say_hello(name) that prints a greeting, anddouble(number) that returns twice itsdouble(7) in a variable and print it.area(width, height) that returns the area of adouble should return its answerOne 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.
Try this: Change the name to Alex and press Run again — the first greeting becomes “Hello, Alex!” and the Sam greeting stays the same.
Press Run to see the output here.
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)
def defines it, calling its name runs it.print shows a value to a human; return hands it back to the program.return never runs — returning ends the function.Next lesson: Mini-Project — The Number-Guessing Game.
describe_pet("Biscuit", "dog"), which argument goes to which parameter?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.