Functions
From the 9D curriculum
Functions
TL;DR
Functions are like mini-programs or recipes that take inputs, do some work, and often give back an output. They help you organize your code, make it reusable, and simplify complex tasks by breaking them down into smaller pieces. Instead of repeating identical code blocks, you can define a function once and call it whenever you need it.
1. The Mental Model
Think of a function as a custom machine you built. You give it specific ingredients (inputs), it performs an action, and then it might produce a result (output). This machine allows you to do the same task multiple times without rebuilding it from scratch.
2. The Core Material
Functions are blocks of organized, reusable code that perform a single, related action. They make your code more modular, readable, and easier to debug.
Defining a Function
To define a function, you typically use a keyword (like def in Python) followed by the function's name, parentheses for parameters, and then a colon. The code inside the function is indented.
def greet_user(name): # 'name' is a parameter
print(f"Hello, {name}!")
def add_numbers(num1, num2):
sum_result = num1 + num2
return sum_result # 'return' sends a value back
def: This keyword tells Python you're defining a new function.greet_user/add_numbers: These are the names of your functions. Choose names that describe what the function does.(name)/(num1, num2): These are the parameters (or arguments). They are placeholders for the values you'll pass into the function when you use it.:: Marks the end of the function header.- The indented lines are the function body, where the actual work happens.
return: This statement is used to send a value back as the function's output. If a function doesn't have an explicitreturnstatement, it implicitly returnsNone.
Calling a Function
To use a function, you "call" it by its name followed by parentheses, providing actual values for its parameters. These actual values are called arguments.
greet_user("Alice") # "Alice" is the argument for the 'name' parameter
# Output: Hello, Alice!
total = add_numbers(5, 3) # 5 and 3 are arguments
print(f"The sum is: {total}")
# Output: The sum is: 8
Parameters and Arguments
- Parameters: The variables listed inside the parentheses in the function definition. They are placeholders.
- Arguments: The actual values you pass into the function when you call it.
You can combine functions to build more complex processes.
graph TD
Start --> A["Get User Name"];
A --> B["Call greet_user(name)"];
B --> C["Get First Number"];
C --> D["Get Second Number"];
D --> E["Call add_numbers(num1, num2)"];
E --> F["Print Result"];
F --> End;
3. Worked Example
Let's create a function that calculates the area of a rectangle.
- Define the function: It needs two pieces of information:
lengthandwidth. It should return their product. - Call the function: Use it to find the area of a specific rectangle.
# Step 1: Define the function
def calculate_rectangle_area(length, width):
"""
This function calculates the area of a rectangle.
It takes length and width as input and returns their product.
"""
area = length * width
return area
# Step 2: Call the function with specific arguments
my_rectangle_length = 10
my_rectangle_width = 5
rectangle_area = calculate_rectangle_area(my_rectangle_length, my_rectangle_width)
print(f"A rectangle with length {my_rectangle_length} and width {my_rectangle_width} has an area of: {rectangle_area}")
# You can call it again with different values
another_area = calculate_rectangle_area(7.5, 3)
print(f"Another rectangle's area is: {another_area}")
Output:
A rectangle with length 10 and width 5 has an area of: 50
Another rectangle's area is: 22.5
4. Key Takeaways
- Functions group related code into a reusable block.
- They take inputs called parameters (in the definition) or arguments (when called).
- The
returnstatement sends a value back from the function. - Functions make your code easier to read, test, and maintain.
- You define a function once, but you can call it many times.
- If a function doesn't explicitly return a value, it returns
Noneby default.
Common Mistakes to Avoid:
- Forgetting the colon : after the def statement.
- Not indenting the code inside the function, leading to IndentationError.
- Forgetting to actually call the function, so its code never runs.
- Confusing parameters (placeholders in definition) with arguments (actual values passed).
- Expecting a function to print something when it only returns a value; you still need a print() call for the return value to show up.
5. Now Try It
Write a function called calculate_circumference that takes one parameter, radius, and returns the circumference of a circle (use 3.14159 for pi). Then, call your function with a radius of 7 and print the result. What does success look like? You'll have a function defined, and when you run your script, it should print the circumference for a radius of 7.
Frequently asked about Functions
More from 9D
Get the full 9D curriculum
Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.
Create Free Account