Python Functions
Learn how to define your own functions using def, pass parameters, return values, and understand variable scope.
What Are Functions?
A function is a reusable block of code that performs a specific task. Instead of writing the same code over and over, you define a function once and call it whenever you need it. You have already used built-in functions like print() and len() -- now you will learn to create your own.
Functions help keep your code organised, readable, and DRY (Don't Repeat Yourself). In Python, you define a function with the def keyword:
# Defining a simple function
def greet():
print("Hello! Welcome to BrightPath.")
# Calling the function
greet() # Output: Hello! Welcome to BrightPath.
greet() # You can call it as many times as you like
The indented code under def is the function body. It only runs when you call the function by writing its name followed by parentheses.
Parameters and Arguments
Functions become much more powerful when you give them parameters -- placeholders for data that the function will use. When you call the function, you pass arguments (actual values) into those parameters.
# Function with parameters
def greet_student(name, year):
print(f"Hello {name}! Welcome to Year {year}.")
greet_student("Mia", 10) # Output: Hello Mia! Welcome to Year 10.
greet_student("Liam", 9) # Output: Hello Liam! Welcome to Year 9.
# Default parameter values
def power(base, exponent=2):
return base ** exponent
print(power(5)) # Output: 25 (uses default exponent=2)
print(power(5, 3)) # Output: 125 (exponent overridden to 3)
You can set default values for parameters. If the caller does not provide a value, the default is used. Parameters with defaults must come after parameters without defaults.
Return Values and Variable Scope
The return statement sends a value back to the caller. Without a return statement, a function returns None by default.
# Function that returns a value
def calculate_area(length, width):
area = length * width
return area
result = calculate_area(8, 5)
print(f"The area is {result} square units.") # Output: The area is 40 square units.
# Variable scope: local vs global
total = 0 # Global variable
def add_score(points):
bonus = 10 # Local variable -- only exists inside this function
return points + bonus
print(add_score(50)) # Output: 60
# print(bonus) # ERROR! 'bonus' is not defined outside the function
Scope determines where a variable can be accessed. Variables created inside a function are local -- they exist only while the function runs. Variables created outside all functions are global and can be read anywhere, but modifying them inside a function requires the global keyword.
Key Vocabulary
Function
A reusable block of code defined with def that performs a specific task when called.
Parameter
A variable listed in the function definition that acts as a placeholder for data passed in when the function is called.
Return Value
The result sent back by a function using the return keyword, which the caller can store or use.
Scope
The region of code where a variable is accessible. Local scope is inside a function; global scope is outside all functions.
Worked Examples
Write a function that takes a student's name and score, then prints a message.
def show_result(name, score):
if score >= 50:
print(f"Well done {name}! You passed with {score}%.")
else:
print(f"Keep trying {name}. You scored {score}%.")
show_result("Ava", 85) # Output: Well done Ava! You passed with 85%.
show_result("Tom", 42) # Output: Keep trying Tom. You scored 42%.
Step 1: Define the function with two parameters: name and score.
Step 2: Use an if/else to decide which message to print.
Step 3: Call the function with different arguments to test both branches.
Write a function that returns the average of three numbers.
def average(a, b, c):
total = a + b + c
return total / 3
result = average(80, 90, 70)
print(f"Average: {result}") # Output: Average: 80.0
Step 1: Define a function with three parameters.
Step 2: Calculate the total, then divide by 3 and return the result.
Step 3: Store the returned value in a variable and print it.
Demonstrate local vs global scope.
school = "BrightPath" # Global variable
def welcome():
greeting = "Welcome to" # Local variable
return f"{greeting} {school}"
print(welcome()) # Output: Welcome to BrightPath
print(school) # Output: BrightPath
# print(greeting) # ERROR -- greeting is local to welcome()
Step 1: school is global -- accessible everywhere.
Step 2: greeting is local -- it only exists inside welcome().
Step 3: Trying to access greeting outside the function causes a NameError.
Knowledge Check
Select the correct answer for each question. Click "Check Answer" to see if you are right.
Question 1
Which keyword is used to define a function in Python?
Question 2
What does the following function return?
def double(n):
return n * 2
result = double(7)
Question 3
What is the difference between a parameter and an argument?
Question 4
What happens if a function does not have a return statement?
Question 5
A variable created inside a function is called a:
Key Concepts Summary
- ●A function is defined with
def function_name():and called withfunction_name(). - ●Parameters are placeholders in the definition; arguments are the actual values passed in.
- ●The return statement sends a value back to the caller. Without it, the function returns
None. - ●Local variables exist only inside their function; global variables are accessible everywhere.
- ●Functions make code reusable, organised, and easier to debug.