Module 4

Functions

Functions are reusable recipes for your code — learn parameters, return values, scope, and when to write your own instead of repeating yourself.

💡What You'll Build
By the end of this module, you will write your own functions with parameters, return values, and default arguments. You will build a temperature converter, a password validator, and a BMI calculator — each as a clean, reusable function you can call from anywhere.

The McDonald's lesson in reusability

In 1948, the McDonald brothers redesigned their restaurant around one idea: a system where every burger was made the same way, every time. They did not reinvent the burger for each customer. They wrote a recipe once — specific ingredients, specific steps, specific timing — and then followed it thousands of times a day. Any new employee could learn the recipe and produce the exact same result.

That is what a function is in programming. A function is a recipe: a named block of code you write once and use whenever you need it. Instead of copying and pasting the same 10 lines of code in five places, you write a function once and call it five times.

The McDonald brothers' system turned a small restaurant into a global empire. Functions turn messy, repetitive code into clean, professional software.

Remember the guessing game you built in Module 3? All the code lived in one place — the game logic, the input handling, the win/loss messages. If you wanted a similar game with different rules, you would have to copy and paste everything. Functions fix that.

python
# Without a function — copy-pasted code
print("=" * 30)
print("RECEIPT")
print("=" * 30)

# ... 50 lines later, you need the same header again
print("=" * 30)
print("RECEIPT")
print("=" * 30)

# With a function — write once, use anywhere
def print_header():
    print("=" * 30)
    print("RECEIPT")
    print("=" * 30)

print_header()  # First use
print_header()  # Second use — no duplication

1time you write it

100xtimes you can call it

1 placeto update when you change it

Anatomy of a function

A function has four parts:

python
def greet(name):            # def, name, parameter
    message = f"Hello, {name}!"   # body — the work
    return message            # return value — the output

result = greet("Sarah")     # calling the function
print(result)               # Hello, Sarah!
PartWhat it isAnalogy
defKeyword that starts a function definition"Here is a new recipe"
Function nameWhat you call it (greet)Recipe title ("Chocolate Cake")
ParametersInputs the function needs (name)Ingredients ("2 cups flour")
returnThe output the function producesThe finished dish

Step 1: Define — Use def to create the function. This does NOT run the code — it just saves the recipe.

Step 2: Call — Use the function name with parentheses: greet("Sarah"). NOW the code runs.

Step 3: Receive — The return value comes back to wherever you called the function. Store it in a variable or use it directly.

🔑Defining is not running
The most common beginner confusion: writing `def greet(name):` does NOT print anything. It only saves the recipe. You must CALL the function (`greet("Sarah")`) to actually execute it. Think of writing a recipe card versus actually cooking the recipe — two completely different actions.

Parameters and arguments

Parameters are the variables listed in the function definition. Arguments are the actual values you pass when calling it.

python
def calculate_tip(bill, tip_percent):    # bill and tip_percent are parameters
    tip = bill * (tip_percent / 100)
    total = bill + tip
    return total

result = calculate_tip(50.00, 20)       # 50.00 and 20 are arguments
print(f"Total: ${result:.2f}")           # Total: $60.00

Default parameters

You can give parameters default values so callers do not always have to specify them:

python
def calculate_tip(bill, tip_percent=18):    # 18 is the default
    tip = bill * (tip_percent / 100)
    return bill + tip

print(calculate_tip(50))         # Uses default 18% → $59.00
print(calculate_tip(50, 25))     # Overrides with 25% → $62.50

Keyword arguments

When a function has multiple parameters, you can name them explicitly for clarity:

python
def create_user(name, age, city):
    print(f"{name}, {age}, from {city}")

# Positional — order matters
create_user("Alice", 30, "London")

# Keyword — order does not matter
create_user(city="Tokyo", name="Bob", age=25)

There Are No Dumb Questions

"What is the difference between print() and return?"

print() displays text on the screen — it is for humans to read. return sends a value back to the calling code — it is for your program to use. A function that prints but does not return produces no usable output. A function that returns but does not print produces no visible output. You often need both: compute a result with return, then print it where you called the function.

"Can a function return multiple values?"

Yes. Use a comma: return tip, total. Python packs them into a tuple. Unpack them: tip, total = calculate_tip(50). This is a very common Python pattern.

🔒

Write Your First Function

25 XP

Write a function called `celsius_to_fahrenheit` that: 1. Takes a Celsius temperature as a parameter 2. Converts it using the formula: F = (C * 9/5) + 32 3. Returns the Fahrenheit value Test it: ```python print(celsius_to_fahrenheit(0)) # Should print 32.0 print(celsius_to_fahrenheit(100)) # Should print 212.0 print(celsius_to_fahrenheit(37)) # Should print 98.6 ``` _Hint: The function body is one line: `return (celsius * 9/5) + 32`_

Sign in to earn XP

Return values — functions that produce output

A function without return returns None — Python's way of saying "nothing."

python
def greet(name):
    print(f"Hello, {name}!")    # Prints but returns nothing

result = greet("Alice")
print(result)                    # None

def calculate_area(length, width):
    return length * width        # Returns a usable value

area = calculate_area(5, 3)
print(area)                      # 15

You can use return values directly in expressions:

python
def double(n):
    return n * 2

print(double(5) + double(3))   # 10 + 6 = 16

Early return — exit a function early

python
def divide(a, b):
    if b == 0:
        return "Error: cannot divide by zero"
    return a / b

print(divide(10, 3))   # 3.333...
print(divide(10, 0))   # Error: cannot divide by zero

Scope — where variables live and die

Scope is about where a variable exists. Think of it like rooms in a house: a lamp in the bedroom only lights up the bedroom, not the kitchen.

python
name = "Global Alice"           # Global scope — accessible everywhere

def greet():
    name = "Local Bob"          # Local scope — only exists inside this function
    print(name)                  # "Local Bob"

greet()
print(name)                      # "Global Alice" — unchanged

Global Scope

  • Created outside any function
  • Accessible everywhere in the file
  • Lives for the entire program
  • Think: house-wide lighting

Local Scope

  • Created inside a function
  • Only accessible inside that function
  • Dies when the function ends
  • Think: bedroom lamp

⚠️Do not rely on global variables
You CAN read global variables from inside a function. But modifying them requires the `global` keyword, and doing so is considered bad practice. Functions should communicate through parameters (input) and return values (output) — not by reaching out to grab global variables. This makes your code predictable and testable.

There Are No Dumb Questions

"Why does Python delete local variables when a function ends?"

Memory management. If every variable from every function call lived forever, your program would eventually run out of memory. Local variables are like scratch paper — you use them to solve a problem, then throw them away. The return value is the answer you keep.

"What if I need a function to remember something between calls?"

For now, return the value and pass it back in next time. Later, you will learn about classes (objects that bundle data and functions together). For this course, parameters and return values are all you need.

Built-in functions you already know

Python comes with dozens of built-in functions. You have been using some already:

python
# Type conversion
int("42")           # 42
float("3.14")       # 3.14
str(100)            # "100"
bool(0)             # False

# Math
len("Hello")        # 5 (length)
max(3, 7, 1)        # 7
min(3, 7, 1)        # 1
abs(-5)             # 5 (absolute value)
round(3.7)          # 4
sum([1, 2, 3, 4])   # 10

# Input/Output
print("Hello")      # Display text
input("Name: ")     # Get user input

# Utility
type(42)            # <class 'int'>
range(5)            # 0, 1, 2, 3, 4
sorted([3, 1, 2])   # [1, 2, 3]

🔒

Function Composition

25 XP

Using ONLY built-in functions, write a single line that: 1. Takes the list `[4, -2, 7, -1, 3]` 2. Gets the absolute value of the minimum 3. Prints the result Expected output: `1` Now write a function called `average` that takes a list of numbers and returns their average (mean). ```python def average(numbers): # Your code here — use sum() and len() pass print(average([90, 85, 92, 88])) # Should print 88.75 ``` _Hint: Average = sum of all numbers / count of numbers. Python has `sum()` and `len()` built in._

Sign in to earn XP

Putting it together — a password validator

Here is a practical function that combines everything from this module:

python
def validate_password(password):
    if len(password) < 8:
        return "Too short — must be at least 8 characters"

    has_upper = False
    has_digit = False

    for char in password:
        if char.isupper():
            has_upper = True
        if char.isdigit():
            has_digit = True

    if not has_upper:
        return "Must contain at least one uppercase letter"
    if not has_digit:
        return "Must contain at least one digit"

    return "Password is valid!"

# Test it
print(validate_password("short"))        # Too short
print(validate_password("alllowercase1"))  # No uppercase
print(validate_password("NoDigits"))      # No digit
print(validate_password("GoodPass1"))     # Valid!

This function uses: parameters, return values, early returns, a for loop, if statements, string methods, and a boolean pattern. Every concept from modules 1-4 in one real function.

<classifychallenge xp="25" title="print() or return?" items={["Display a greeting message to the user","Calculate a tip amount for other code to use","Show an error message in the terminal","Compute an average that will be stored in a variable","Log the current step of a process for debugging","Generate a formatted report string for saving to a file"]} options={["print()","return"]} hint="print() is for showing output to humans on the screen. return is for sending a value back to the calling code so the program can use it. If the result needs to be stored, calculated with, or passed to another function, use return. If it just needs to appear on screen, use print().">

🔒

Build a BMI Calculator

50 XP

Write a function called `calculate_bmi` that: 1. Takes `weight_kg` and `height_m` as parameters 2. Calculates BMI: weight / (height ** 2) 3. Returns a string with the BMI and category: - Under 18.5: "Underweight" - 18.5 - 24.9: "Normal" - 25.0 - 29.9: "Overweight" - 30.0+: "Obese" Example output: ```python print(calculate_bmi(70, 1.75)) # "BMI: 22.9 — Normal" ``` _Hint: Calculate BMI first, then use if/elif/else to determine the category. Use an f-string to format the return value. Round BMI to 1 decimal with `round(bmi, 1)`._

Sign in to earn XP

Back to McDonald's

The McDonald brothers did not invent the hamburger. They invented a system — a recipe that any employee could follow to produce the same result, every time. That is exactly what functions give you: a system for your code. Write the recipe once, call it wherever you need it, update it in one place.

Your validate_password function uses everything from the first four modules: variables, type checking, loops, conditionals, and now functions. Each module has added a new layer of capability. The next layer will give you the containers to organize all this data.

Next up: Right now, your functions take single values — one number, one string. But what if you need to process a list of 500 students, a dictionary of product prices, or a set of unique tags? In the next module, you will learn data structures — Python's built-in containers for organizing collections of data.

Key takeaways

  • Functions are reusable recipes — write once, call many times, update in one place
  • def defines a function, calling it (with parentheses) runs it — defining is NOT running
  • Parameters are inputs; return values are outputs — this is how functions communicate
  • Default parameters let callers skip arguments: def greet(name="World")
  • return sends a value back to the caller; print() just displays text — they are not interchangeable
  • Scope: local variables die when the function ends; communicate through parameters and returns, not globals
  • Built-in functions like len(), sum(), max(), sorted() save you from reinventing the wheel

Try it yourself

Experiment with functions in this playground:

Now write a function that passes the tests:

?

Knowledge Check

1.What is the output of this code? ```python def add(a, b): return a + b result = add(3, 4) print(result) ```

2.What does a function return if it has no `return` statement?

3.What is the output? ```python x = 10 def change(): x = 20 print(x) change() print(x) ```

4.Which of the following correctly uses a default parameter?

Want to go deeper?

💻 Software Engineering Master Class

The complete software engineering program — from your first line of code to landing your first job.

View the full program