Tech With Galvan

πŸ§ͺ Practice: Functions

30 min β€’ Beginner β€’ Module 7

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.

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.)

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”.

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:

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:

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:

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

Solutions

Exercise 1:

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:

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:

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:

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:

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:

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.