logs/s01.md
logs/s02.md
logs/s04.md
int
float
17 % 5
/
//
x
student_count
Why functions matter:
Functions are the building blocks of programs.
A function is a named sequence of statements that performs a computation.
You've already used functions:
print("Hello") # print is a function len("Hello") # len is a function type(42) # type is a function
Now you'll learn to create your own.
def greet(name): """Display a greeting message.""" message = f"Hello, {name}!" print(message)
def
greet
name
"""..."""
Define once, use many times:
# Define the function def greet(name): """Display a greeting message.""" print(f"Hello, {name}!") # Call it multiple times greet("Alice") # → Hello, Alice! greet("Bob") # → Hello, Bob! greet("Class") # → Hello, Class!
def calculate_tip(bill, percentage): # parameters tip = bill * percentage / 100 print(f"Tip: ${tip:.2f}") calculate_tip(50, 20) # arguments: 50 and 20
Functions can give back a result:
def calculate_tip(bill, percentage): """Calculate tip amount.""" return bill * percentage / 100 # Now we can use the result my_tip = calculate_tip(50, 20) print(f"Tip: ${my_tip}")
Key distinction:
print()
return
# This RETURNS a value def add(a, b): return a + b result = add(3, 4) # result is 7 # This PRINTS but returns None def add_print(a, b): print(a + b) result = add_print(3, 4) # prints 7, but result is None
Most useful functions return values.
def calculate_bmi(weight_kg, height_m): """ Calculate Body Mass Index (BMI). Parameters: weight_kg: Weight in kilograms height_m: Height in meters Returns: BMI value as a float """ return weight_kg / (height_m ** 2)
Always write docstrings — they help you and others understand your code.
# Good: Single purpose def calculate_area(width, height): """Calculate rectangle area.""" return width * height
def process_rectangle(width, height): area = width * height print(f"Area: {area}") perimeter = 2 * (width + height) print(f"Perimeter: {perimeter}") # ... more stuff
Good names describe what the function does:
do_stuff()
calculate_total()
process()
validate_email()
x()
convert_to_celsius()
Pattern: verb_noun or verb_adjective_noun
verb_noun
verb_adjective_noun
get_user_input()
calculate_monthly_payment()
is_valid_email()
def my_function(): x = 10 # x only exists inside this function print(x) my_function() # prints 10 print(x) # ERROR! x doesn't exist here
Open Chapter 3 notebook (chap03.ipynb)
chap03.ipynb
Work through the examples and exercises.
Questions? Ask now!
I'll check:
oim3640
s01.md
s02.md
It's okay if you need more time for Chapter 3 exercises — just show progress!
logs/s05.md
Next session: Functions and Interfaces (Chapter 4)
global styles