Unit 5 · Lesson 1

Defining & Calling Functions

Functions package logic into reusable blocks.

Write functions with def
Understand return vs print()
Follow DRY principle
Add docstrings

Your First Function

A function packages a block of code you can reuse by name:

def greet(name): """Return a greeting string.""" return f"Hello, {name}!" message = greet("Alice") print(message) # Hello, Alice!

return vs print()

return sends a value back to the caller. print() just displays text. Most functions should return values.

DRY = Don't Repeat Yourself. If you write the same code more than twice, make it a function.
Practice Time

Challenges

👋

Challenge 1: Greeting Machine

Guided

Write a function that takes a name and returns a greeting.

Instructions: Write greet(name) that returns "Hello, {name}!".
Hint: return f"Hello, {name}!"
📐

Challenge 2: Area Calculator

Guided

Write functions for rectangle, triangle, and circle area.

Instructions: Write rect_area(w, h), tri_area(b, h), and circle_area(r). Use 3.14159 for pi.
Hint: rect: return width * height, tri: return base * height / 2, circle: return 3.14159 * radius ** 2
🌡

Challenge 3: Temperature Tools

Solo

Write conversion functions between F and C.

Instructions: Write to_celsius(f) = (f-32)*5/9 and to_fahrenheit(c) = c*9/5+32.
Hint: return (f - 32) * 5 / 9 and return c * 9 / 5 + 32
🔧

Challenge 4: Refactor

Stretch

Extract repeated logic into a function.

Instructions: Create calc_total(price, qty, tax_rate) returning price * qty * (1 + tax_rate). Use it for all 3 totals.
Hint: def calc_total(price, qty, tax_rate): return price * qty * (1 + tax_rate)