Python Functions
Learn to define functions, use parameters and return values, understand scope, and set default arguments.
Defining and Calling Functions
A function is a reusable block of code that performs a specific task. You define a function using the def keyword, and then call it by using its name followed by parentheses.
# Defining a function
def greet():
print("Hello! Welcome to Python.")
print("Let's learn together!")
# Calling the function
greet() # Runs the code inside the function
greet() # Can be called multiple times
# Function with parameters
def greet_person(name):
print(f"Hello, {name}! Welcome to Python.")
greet_person("Alice")
greet_person("Bob")
Return Values and Multiple Parameters
Functions can return a value back to the code that called them using the return keyword. This lets you use the result in calculations, assignments, or other functions.
# Function that returns a value
def calculate_area(length, width):
area = length * width
return area
# Using the returned value
room_area = calculate_area(5, 3)
print(f"Room area: {room_area} m2") # Room area: 15 m2
# Function with multiple return values
def get_min_max(numbers):
return min(numbers), max(numbers)
lowest, highest = get_min_max([4, 8, 1, 9, 3])
print(f"Min: {lowest}, Max: {highest}")
Scope and Default Arguments
Scope determines where a variable can be accessed. Variables created inside a function are local and only exist within that function. Default arguments provide fallback values when a parameter is not given.
# Default arguments
def calculate_tip(bill, tip_percent=15):
tip = bill * tip_percent / 100
return round(tip, 2)
print(calculate_tip(50)) # Uses default 15%: $7.5
print(calculate_tip(50, 20)) # Uses 20%: $10.0
# Scope example
message = "I am global" # Global variable
def show_scope():
message = "I am local" # Local variable
print(message) # Prints: I am local
show_scope()
print(message) # Prints: I am global
Key Vocabulary
Function
A reusable block of code defined with def that performs a specific task.
Parameter
A variable listed in the function definition that receives a value when the function is called.
Return Value
The value a function sends back using the return keyword.
Scope
The region of code where a variable is accessible. Local scope is inside a function; global is outside.
Worked Examples
Create a function to calculate a student's grade
def get_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 50:
return "D"
else:
return "F"
# Test the function
students = {"Alice": 92, "Bob": 75, "Charlie": 48}
for name, score in students.items():
grade = get_grade(score)
print(f"{name}: {score}% = Grade {grade}")
Step 1: The function takes a score and returns a grade letter.
Step 2: We call it in a loop for each student. Output: Alice: 92% = Grade A | Bob: 75% = Grade C | Charlie: 48% = Grade F
Function with default argument for temperature conversion
def convert_temp(value, to_unit="celsius"):
if to_unit == "celsius":
result = (value - 32) * 5 / 9
return round(result, 1)
elif to_unit == "fahrenheit":
result = value * 9 / 5 + 32
return round(result, 1)
print(convert_temp(100)) # 100F to C: 37.8
print(convert_temp(37.8, "fahrenheit")) # 37.8C to F: 100.0
Step 1: The default parameter to_unit="celsius" means if you omit it, conversion goes to Celsius.
Step 2: Passing "fahrenheit" overrides the default.
Function that returns statistics about a list
def get_stats(numbers):
total = sum(numbers)
count = len(numbers)
average = total / count
return {
"count": count,
"total": total,
"average": round(average, 2),
"min": min(numbers),
"max": max(numbers)
}
scores = [85, 92, 78, 95, 88]
stats = get_stats(scores)
for key, value in stats.items():
print(f"{key}: {value}")
Step 1: The function calculates multiple statistics and returns a dictionary.
Step 2: We can access each stat from the returned dictionary.
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 a function return if there is no return statement?
Question 3
Given def add(a, b=10): return a + b, what does add(5) return?
Question 4
What is a variable created inside a function called?
Question 5
What is the difference between a parameter and an argument?
Key Concepts Summary
-
●
Define functions with
def function_name(parameters):. -
●
Use
returnto send a value back to the caller. - ● Parameters are in the definition; arguments are the values you pass in.
-
●
Default arguments provide fallback values:
def f(x, y=10). - ● Local variables exist only inside their function; global variables are accessible everywhere.