Functions
Write once, use anywhere
📖 Concept Recap
- def defines a function. return sends a value back to the caller.
- Default parameters make arguments optional:
def greet(name, greeting="Hello") - Multiple return values:
return a, breturns a tuple — unpack withx, y = func() - Good functions do ONE thing and do it well. Name them with verbs:
calculate_total(),format_name(). - Docstrings (optional but good): describe what a function does with a string on the first line inside.
👀 Worked Example
A BMI calculator with default parameters and multiple return values:
Exercise 1 — Temperature Converter
Complete the temperature converter by filling in the blanks. The formulas are:
- F to C:
(F - 32) × 5/9 - C to F:
C × 9/5 + 32 - C to K:
C + 273.15 - K to C:
K - 273.15
5/9 gives a float automatically. You can write 5/9 directly.Exercise 2 — List Statistics
Write a function summarize_list(numbers) that takes a list of numbers and returns a dictionary with these keys: min, max, sum, average, count, range (max - min).
Test it with: [4, 8, 15, 16, 23, 42] and print all the results neatly.
min(), max(), sum(), len(). Return a dict: return {"min": ..., "max": ..., ...}Exercise 3 — Table Formatter
Write a function format_table(headers, rows) that prints data as a formatted table with | separators and a header divider line. Example output:
str(val).ljust(width) or rjust(width) for alignment. Join columns with " | ".join(...).Mini Project — Unit Converter Toolkit
Build a toolkit of 4 converter functions. Then write a master function that runs all four on any input value and prints a neat summary. Test with value = 100.
miles_to_km(miles)— 1 mile = 1.60934 kmkg_to_lbs(kg)— 1 kg = 2.20462 lbscelsius_to_fahrenheit(c)— standard formulausd_to_eur(usd, rate=0.92)— with a default exchange raterun_conversions(value)— runs all four and prints a formatted summary
run_conversions function calls all four and uses f-strings to print results. E.g.: print(f"100 miles = {miles_to_km(100):.2f} km")✅ Lab 4 Complete!
You’ve built functions with default parameters, multiple return values, and created a reusable toolkit. Functions are the key to writing code that’s clean, testable, and reusable.
Continue to Lab 5: Lists & Dictionaries →