Unit 3 • Lesson 1

What Are Functions and Why Use Them

Overview

Functions let you group instructions into reusable blocks that make programs shorter and clearer. You'll understand how functions improve structure, reduce repetition, and make collaboration easier, while also learning when and why to use them in your Python programs.

Beginner 15–20 min

What You Will Learn in This Lesson

By the end of this lesson, you will know:

  • What functions are: Understand how functions group code into reusable blocks.
  • Why functions are useful: Learn how functions make code shorter, clearer, and easier to maintain.
  • When to use functions: Recognize situations where functions improve your code.
  • Built-in functions: Discover functions Python provides that you've already been using.

Why This Matters

Functions are one of the most important concepts in programming. They let you write code once and use it many times, organize your code into logical pieces, and make programs easier to understand and fix. Almost every program you write will use functions - both ones you create and ones Python provides.

Step 1: What Are Functions?

A function is a named block of code that performs a specific task. Think of it like a recipe - you write the recipe once (define the function), and then you can follow it whenever you need to make that dish (call the function). Functions let you organize code into reusable pieces.

Without Functions (Repetitive)

You'd have to write the same code multiple times:

# Calculate area three times
length1 = 5
width1 = 3
area1 = length1 * width1
print(area1)

length2 = 7
width2 = 4
area2 = length2 * width2
print(area2)

length3 = 6
width3 = 2
area3 = length3 * width3
print(area3)

Lots of repeated code

With Functions (Efficient)

Write it once, use it many times:

def calculate_area(length, width):
    return length * width

print(calculate_area(5, 3))
print(calculate_area(7, 4))
print(calculate_area(6, 2))

Much cleaner and reusable

Key Concept: Functions are like mini-programs within your program. They take inputs (called parameters), do something with them, and optionally return a result. Once you define a function, you can call it from anywhere in your code, as many times as you want.

Step 2: Why Use Functions?

Functions solve several problems that come up when programming:

1

Reduce Repetition

Instead of writing the same code multiple times, you write it once in a function and call it whenever you need it.

# Instead of repeating:
def greet():
    print("Hello!")
    print("Welcome!")

greet()  # Use it many times
greet()
greet()
2

Organize Code

Functions break your program into logical pieces. Each function does one specific thing, making your code easier to understand.

# Clear organization:
def get_user_input():
    # Get input from user
    
def process_data():
    # Process the data
    
def display_results():
    # Show results
3

Easier to Fix

If you need to change how something works, you only change it in one place (the function definition) instead of many places.

# Fix once, works everywhere:
def calculate_total(price, tax):
    return price + (price * tax)
    # Change this formula once,
    # affects all calculations

Mini Practice #1: See the Difference

Try It Yourself

Compare code without functions vs. with functions:

Press Run to see output

What happened? Both approaches produce the same output, but notice the difference. Without a function, you need to write the same three print statements three times (9 lines total). With a function, you define the greeting once (4 lines), then call it three times (3 lines). The function version is shorter, easier to read, and if you wanted to change the greeting message, you'd only change it in one place instead of three! This is the power of functions.

Step 3: Built-in Functions You Already Know

Python comes with many built-in functions that you've already been using. These are functions that Python provides for common tasks:

Common Built-in Functions
# print() - displays output
print("Hello, World!")

# len() - gets length of a string or list
name = "Python"
print(len(name))  # Output: 6

# input() - gets input from user
# name = input("What's your name? ")

# type() - shows the type of a value
print(type(5))      # Output: 
print(type("hi"))   # Output: 

# int(), float(), str() - convert types
number = int("42")
text = str(42)

How Built-in Functions Work

When you write print("Hello"), you're calling a function named print that Python provides. The function takes the text "Hello" as input (called an argument), performs the task of displaying it, and returns nothing (it just prints). You don't need to write the code for print - Python already has it built in. You can create your own functions the same way!

Step 4: When to Use Functions

Here are common situations where functions are helpful:

Common Function Use Cases
# 1. Repeating the same code multiple times
def calculate_tip(amount):
    return amount * 0.15

tip1 = calculate_tip(20)
tip2 = calculate_tip(35)
tip3 = calculate_tip(50)

# 2. Organizing code into logical pieces
def get_user_info():
    # Get name, age, etc.
    pass

def validate_info():
    # Check if info is valid
    pass

def save_info():
    # Save to database
    pass

# 3. Making code easier to understand
def calculate_total(items):
    # Clear what this does
    total = 0
    for item in items:
        total = total + item.price
    return total

Rule of Thumb: If you find yourself writing the same code more than once, or if you have a block of code that does one specific thing, consider making it a function. Functions make your code cleaner, more maintainable, and easier to test.

Step 5: Function Structure

All functions in Python follow a similar structure. Understanding this structure helps you read and write functions correctly:

Basic Function Structure
def function_name():
    # Function body - code that runs
    print("This code runs when function is called")
    # More code here

# After defining, call the function:
function_name()
1

Function Definition

Start with def followed by the function name and parentheses. End with a colon :.

2

Function Body

The indented code after the colon is the "function body" - this is what gets executed when the function is called.

3

Function Call

To use the function, write its name followed by parentheses. This "calls" or "invokes" the function, running its code.

Remember: Defining a function doesn't run it - it just tells Python what the function does. You must call the function (write its name with parentheses) to actually execute the code inside it.

End-of-Lesson Exercises

Exercise 1: Identify Built-in Functions

Write code that uses three different built-in functions: print(), len(), and type(). Print the length of the string "Python" and its type.

Use print(len("Python")) and print(type("Python")).

Write your code above and click "Check Answer" to verify it's correct.