Courses/Python Mastery/Module 7: Functions
Module 7 ยท Lesson 630 minBeginner๐Ÿงช Practice Session

๐Ÿงช Practice: Functions

Lesson goal
Write 8 functions from specs โ€” temperature converter, is_prime, calculator, and more.

๐Ÿงช Practice: Functions

Six exercises that turn function theory into function instinct. Solutions at the bottom โ€” write first, peek second.

Exercise 1 โ€” The temperature converter

Write celsius_to_fahrenheit(c) (formula: c * 9/5 + 32) and its reverse. Round to 1 decimal.

code
print(celsius_to_fahrenheit(37))    # 98.6
print(fahrenheit_to_celsius(212))   # 100.0

Exercise 2 โ€” is_prime

Write is_prime(n) returning True/False. A prime is divisible only by 1 and itself. (Hint: check divisors from 2 to n-1; % tells you if divisible.)

code
print(is_prime(7))     # True
print(is_prime(10))    # False
print(is_prime(2))     # True

Exercise 3 โ€” Flexible calculator

Write calculate(a, b, operation="+") supporting "+", "-", "*", "/" with a default. Division by zero should return the string "Cannot divide by zero".

code
print(calculate(10, 5))               # 15
print(calculate(10, 5, "*"))          # 50
print(calculate(10, 0, "/"))          # Cannot divide by zero

Exercise 4 โ€” The flexible greeting (args)

Write greet_all(greeting, *names) that greets every name with the given greeting:

code
greet_all("Hello", "Aarav", "Diya")
# Hello, Aarav!
# Hello, Diya!

Exercise 5 โ€” Fix the broken function

This function should return the total, but something's wrong:

code
def total_price(price, qty=1, discount=0):
    total = price * qty
    total = total - discount
    print(total)

result = total_price(100, 2, 10)
print(result * 2)     # crashes or prints None*2!

Exercise 6 โ€” Word analyzer (kwargs)

Write analyze(**stats) that prints each stat nicely:

code
analyze(words=500, pages=2, minutes=4)
# words: 500
# pages: 2
# minutes: 4

Solutions

Exercise 1:

code
def celsius_to_fahrenheit(c):
    return round(c * 9 / 5 + 32, 1)

def fahrenheit_to_celsius(f):
    return round((f - 32) * 5 / 9, 1)

Exercise 2:

code
def is_prime(n):
    if n < 2:
        return False
    for divisor in range(2, n):
        if n % divisor == 0:
            return False
    return True

(Works correctly. A speed upgrade โ€” checking only to โˆšn โ€” comes when you're comfortable.)

Exercise 3:

code
def calculate(a, b, operation="+"):
    if operation == "+":
        return a + b
    elif operation == "-":
        return a - b
    elif operation == "*":
        return a * b
    elif operation == "/":
        if b == 0:
            return "Cannot divide by zero"
        return a / b
    return "Unknown operation"

Exercise 4:

code
def greet_all(greeting, *names):
    for name in names:
        print(f"{greeting}, {name}!")

Exercise 5: Two bugs: the function prints instead of returning, so result is None. Fix:

code
def total_price(price, qty=1, discount=0):
    total = price * qty
    total -= discount
    return total       # โ† return, not print

result = total_price(100, 2, 10)
print(result * 2)      # 380

The print-vs-return distinction โ€” the #1 function bug, now caught by you.

Exercise 6:

code
def analyze(**stats):
    for key, value in stats.items():
        print(f"{key}: {value}")

โœ… Module 7 Checkpoint

Functions: defined, defaulted, flexed, scoped, and one-lined. Every app from here on is built from them.

Next module: Errors & Files โ€” what happens when things go wrong, and how to make data survive.