Functions: Reusable Blocks

Python for Absolute Beginners · Lesson 15

What you’ll learn

1 / 14

A function is a named block of code

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

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

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

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

11 / 14

Key takeaways

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.