Creating Functions in Python
Learn how to define and use your own custom functions in Python. This guide covers function syntax, parameters, return values, separating functions into modules, and returning multiple values.
import { Callout } from '@/components/callout';
Creating Functions in Python
While Python has many built-in functions, its real power comes from allowing you to define your own. A function is a reusable block of code that performs a specific task. It only runs when it is called, can accept data (known as parameters), and can return data as a result.
Functions are the primary tool for organizing and structuring your code, making it more modular, readable, and maintainable. Functions you create work just like the built-in ones you've already used, such as print()
or len()
.
Scripts vs. Functions
It's important to understand the difference between a simple script and a program built with functions.
-
Scripts
- A collection of commands executed sequentially, as if you typed them in the editor.
- Primarily used for automating simple, repetitive tasks.
- All variables exist in the same global workspace.
-
Functions
- Operate on specific inputs (parameters) and produce outputs (return values).
- Have their own separate workspace; internal variables are local and don't interfere with the rest of the program.
- Designed for reusability and abstraction.
Basic Function Syntax
In Python, a function is defined using the def
keyword, followed by the function name, parentheses ()
, and a colon :
. The code block within the function is indented. The return
statement is used to send a value back from the function.
def function_name(parameter1, parameter2):
# Code block to be executed
statement_1
statement_2
return result
<Example title="A Simple add
Function">
This function takes two numbers, x
and y
, as parameters and returns their sum.
# Define the function
def add(x, y):
return x + y
# Call the function with arguments
x_val = 2
y_val = 5
z = add(x_val, y_val)
print(z) # Output: 7
</Example>
Organizing Code: Functions in Separate Files
For better organization, you can define your functions in one file and call them from another. A file containing function definitions is called a module.
<Example title="Creating and Importing a Custom Module"> Let's create a module with a function that calculates an average.
1. Create the module file (myfunctions.py
):
Save this code in a file named myfunctions.py
. This function takes two numbers and returns their average.
# Filename: myfunctions.py
def average(x, y):
return (x + y) / 2
2. Create the main script file (testaverage.py
):
In a separate file, you can import
your average
function from the myfunctions
module and use it.
# Filename: testaverage.py
# Import the specific function from our module
from myfunctions import average
a = 2
b = 3
# Call the imported function
c = average(a, b)
print(c) # Output: 2.5
</Example>
Functions with Multiple Return Values
A Python function can return multiple values by separating them with a comma in the return
statement. This is a powerful feature for bundling related results.
<Example title="Calculating Statistics"> This function takes a list of data and returns both the total sum and the mean.
# Define a function that returns two values
def calculate_stats(data_list):
total_sum = 0
for x in data_list:
total_sum = total_sum + x
n = len(data_list)
mean = total_sum / n
return total_sum, mean
# A list of data
data = [1, 5, 6, 3, 12, 3]
# Call the function and unpack the returned values into two variables
sum_val, mean_val = calculate_stats(data)
print(f"Sum: {sum_val}, Mean: {mean_val}")
# Output: Sum: 30, Mean: 5.0
</Example>
Exercises
The best way to learn is by doing. Try solving the following problems.
<Exercise title="Calculate Average Function">
Create a function named calc_average
that takes two numbers as input and returns their average. Test it to make sure it works.
</Exercise>
<Exercise title="Angle Conversion Functions">
Most trigonometric functions in Python's math
module work with radians. Create your own module with two functions:
degrees_to_radians(d)
: Converts an angle from degrees to radians.radians_to_degrees(r)
: Converts an angle from radians to degrees.
The conversion formulas are:
- $r[\text{radians}] = d[\text{degrees}] \times (\frac{\pi}{180})$
- $d[\text{degrees}] = r[\text{radians}] \times (\frac{180}{\pi})$
Test both functions to ensure they work correctly. (Hint: math.pi
provides the value of $\pi$).
</Exercise>
<Exercise title="Fibonacci Function">
Create a function that implements the Fibonacci sequence. The function should take an integer N
as a parameter and return a list containing the first N
Fibonacci numbers. The sequence begins 0, 1, 1, 2, 3, 5, ...
, where each subsequent number is the sum of the previous two.
</Exercise>
<Exercise title="Prime Number Checker">
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Create a function is_prime(number)
that takes an integer as input and returns True
if the number is prime, and False
otherwise. (Hint: You may need to use nested loops).
</Exercise>