LESSON 7

Functions

Learning objective: Create reusable functions with def.

Understand

Functions package logic you can reuse.

Define a function with def, give it parameters, and use return to send back a result. Functions keep programs organized and avoid repetition.

Analogy: A function is a recipe: define the steps once, then use it whenever you need.

See It in Action

A function with a return value:

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

print(add(2, 3))  # 5
How it works: add takes two parameters and returns their sum, which is then printed.

Try It Yourself

  1. Define a function that greets a name.
  2. Call it with two different names.
  3. Write a function that returns a value.

Quick Quiz

Which keyword defines a Python function?

Challenge

Write a function that returns the larger of two numbers.

Success condition: Your function returns the correct larger value.