Block 5: Defining Functions
Define and call reusable functions with parameters and return values.
Concepts
- def function_name(params): syntax
- return keyword vs print()
- Default parameter values
- Calling functions with positional vs keyword args
Code Examples
Basic function
def add(a, b):
return a + b
print(add(3, 5)) # 8
Default parameters
def greet(name, greeting='Hello'):
return f'{greeting}, {name}'
print(greet('Alice')) # Hello, Alice
print(greet('Bob', 'Hi')) # Hi, Bob
Exercise
Define compute_bmi(weight_kg, height_m) and test on 3 people. Write a greet(name, greeting='Hello') function.
Solution
def compute_bmi(weight_kg, height_m):
return weight_kg / (height_m ** 2)
def greet(name, greeting='Hello'):
return f'{greeting}, {name}!'
# Test
people = [(70, 1.75), (60, 1.65), (90, 1.80)]
for w, h in people:
print(f'BMI: {compute_bmi(w, h):.1f}')
print(greet('Alice'))
print(greet('Bob', 'Hi'))Practice Problems
Problem 1: Write a function celsius_to_fahrenheit(c) that converts and returns the value.
Hint: F = C * 9/5 + 32
Problem 2: Write a function with a default argument that can be overridden.
Hint: def f(x, multiplier=2): return x * multiplier
Application
Functions modularize code—data cleaning, feature engineering, and model evaluation are typically separate functions.
Case Study
A ML pipeline has functions: load_data(), preprocess(), train_model(), evaluate(). Each is tested independently and composed in main().
Homework
Write a function that takes a list of numbers and returns (min, max, average) as a tuple.