guidebeginner20 min
Functions: Reusable Code
Package code into reusable functions. Understand parameters, return values, and scope.
Prerequisites
Last updated: Jan 28, 2026
Functions are reusable blocks of code. Instead of writing the same code multiple times, you define it once as a function and call it whenever you need it.
Defining a Function
python
def greet():
print("Hello!")
print("Welcome to Python")
# Call the function
greet()
greet() # Can call it as many times as you wantOutput:
text
Hello!
Welcome to Python
Hello!
Welcome to PythonThe def keyword defines a function. The code inside only runs when you call the function.
Parameters: Passing Data In
Functions can accept input through parameters:
python
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob") # Hello, Bob!
# Multiple parameters
def greet_full(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
greet_full("Alice", "Smith") # Hello, Alice Smith!Return Values: Getting Data Out
Functions can return a value using return:
python
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
# Use the result directly
print(add(10, 20)) # 30
# Return ends the function
def divide(a, b):
if b == 0:
return "Cannot divide by zero"
return a / b
print(divide(10, 2)) # 5.0
print(divide(10, 0)) # Cannot divide by zeroDefault Parameters
Parameters can have default values:
python
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Good morning") # Good morning, Bob!
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 (5 squared)
print(power(5, 3)) # 125 (5 cubed)Multiple Return Values
Functions can return multiple values:
python
def get_stats(numbers):
total = sum(numbers)
average = total / len(numbers)
return total, average
numbers = [10, 20, 30, 40, 50]
sum_result, avg_result = get_stats(numbers)
print(f"Sum: {sum_result}, Average: {avg_result}")Scope: Where Variables Live
Variables created inside a function only exist inside that function:
python
def my_function():
x = 10 # Local variable
print(x)
my_function() # 10
# print(x) # ERROR! x doesn't exist here
# Variables outside functions are "global"
y = 20
def another_function():
print(y) # Can read global variables
another_function() # 20Practical Example
python
def calculate_tip(bill_amount, tip_percent=0.18):
"""Calculate tip and total for a restaurant bill."""
tip = bill_amount * tip_percent
total = bill_amount + tip
return tip, total
# Calculate with default 18% tip
tip, total = calculate_tip(50)
print(f"Tip: ${tip:.2f}, Total: ${total:.2f}")
# Tip: $9.00, Total: $59.00
# Calculate with custom 20% tip
tip, total = calculate_tip(50, 0.20)
print(f"Tip: ${tip:.2f}, Total: ${total:.2f}")
# Tip: $10.00, Total: $60.00Docstrings
The triple-quoted string right after def is called a docstring. It documents what the function does:
python
def calculate_area(width, height):
"""
Calculate the area of a rectangle.
Parameters:
width: The width of the rectangle
height: The height of the rectangle
Returns:
The area (width * height)
"""
return width * height
# View docstring with help()
help(calculate_area)Practice
- Write a function that converts Celsius to Fahrenheit
- Write a function that checks if a number is prime
- Write a function that takes a list and returns the minimum and maximum
- Write a function that counts vowels in a string
- Write a function that generates the Fibonacci sequence up to n numbers