"A system that takes in an input, performs an operation, and gives out an output. Think of it as a black box - you don't need to know HOW it works, just WHAT it does."
The Black Box Concept
INPUT
2, 3
→
FUNCTION
add(a, b)
Black Box
→
OUTPUT
5
You don't need to know HOW it adds - just that it does!
Function Anatomy
def function_name(parameter1, parameter2):
# Function body - the code that runs
result = parameter1 + parameter2
return result # Output
# Calling the function
output = function_name(2, 3) # output = 5
Two Parts:
Function Header: Name and parameters (inputs)
Function Body: Code that executes when called
Interactive Function Builder
Function Definition:
Configure inputs and call function
Why Use Functions?
Reusability
Write once, use many times
Organization
Group related code together
Abstraction
Hide complexity, show interface
Real-World Example
# 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"
# Use it many times
grade1 = calculate_grade(95) # "A"
grade2 = calculate_grade(82) # "B"
grade3 = calculate_grade(68) # "F"
Mental Model: Functions are like tools in a toolbox. You reach for the right tool (function) when you need it. You don't rebuild the hammer each time - you just use it.
"Functions let you build your own custom operations. They're fundamental to organizing code and avoiding repetition."
[########################......] 12/15
> [WHY_IT_MATTERS]:
Functions are tools you build yourself. Don't reinvent the wheel—call the function.