add(a, b) is defined, you can call it anywhere without rewriting its internal steps!
def): The function's name and its parameters (input slots)return: The indented instructions that execute and hand back a resultdef function_name(parameter1, parameter2):
# Function body - the code that runs when called
result = parameter1 + parameter2
return result # Hand the output back to the caller
# Calling the function with arguments (2, 3)
output = function_name(2, 3) # output = 5
Write logic once, invoke it as many times as you need.
Group related instructions under a clear, descriptive name.
Hide internal complexity behind a clean input/output interface.
# Define function once
def calculate_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
else:
return "F"
# Reuse it anywhere in your program
grade1 = calculate_grade(95) # "A"
grade2 = calculate_grade(82) # "B"
grade3 = calculate_grade(68) # "F"