๐งช 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.0Exercise 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)) # TrueExercise 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 zeroExercise 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: 4Solutions
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) # 380The 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.