Learn Without Walls
← Back to Module 9

Module 9: Practice Problems

15 problems to reinforce your understanding of functions

Problem 1: Simple Greeting Easy

Write a function called greet(name) that prints "Hello, [name]! Nice to meet you.". Call it with your own name.

Use def greet(name): and an f-string inside. Remember to call the function after defining it.
def greet(name):
    """Greet a person by name."""
    print(f"Hello, {name}! Nice to meet you.")

greet("Alice")

Problem 2: Square a Number Easy

Write a function called square(n) that returns the square of n. Print the result of calling it with 7.

Use return n ** 2 or return n * n.
def square(n):
    """Return the square of n."""
    return n ** 2

print(square(7))  # 49

Problem 3: Maximum of Two Easy

Write a function max_of_two(a, b) that returns the larger of the two numbers (without using Python's built-in max()).

Use an if/else statement to compare a and b.
def max_of_two(a, b):
    """Return the larger of two numbers."""
    if a >= b:
        return a
    else:
        return b

print(max_of_two(10, 20))  # 20
print(max_of_two(7, 3))    # 7

Problem 4: Is Even? Easy

Write a function is_even(n) that returns True if n is even and False otherwise.

A number is even if n % 2 == 0. You can return the result of this comparison directly.
def is_even(n):
    """Return True if n is even."""
    return n % 2 == 0

print(is_even(4))   # True
print(is_even(7))   # False

Problem 5: Full Name Easy

Write a function full_name(first, last) that returns the full name as a single string with proper capitalization.

Use .title() to capitalize each word, and an f-string to combine.
def full_name(first, last):
    """Return a properly capitalized full name."""
    return f"{first.title()} {last.title()}"

print(full_name("alice", "smith"))  # Alice Smith

Problem 6: Temperature Converter Medium

Write a function celsius_to_fahrenheit(celsius) that converts Celsius to Fahrenheit using the formula F = C * 9/5 + 32. Also write fahrenheit_to_celsius(fahrenheit). Test both.

For F to C, the formula is C = (F - 32) * 5/9.
def celsius_to_fahrenheit(celsius):
    """Convert Celsius to Fahrenheit."""
    return celsius * 9 / 5 + 32

def fahrenheit_to_celsius(fahrenheit):
    """Convert Fahrenheit to Celsius."""
    return (fahrenheit - 32) * 5 / 9

print(celsius_to_fahrenheit(100))  # 212.0
print(fahrenheit_to_celsius(72))   # 22.22...

Problem 7: Default Greeting Medium

Write a function greet(name, greeting="Hello") that prints "[greeting], [name]!". Call it with and without the greeting argument.

Set the default value in the function definition. Call with one argument to use the default, or two to override it.
def greet(name, greeting="Hello"):
    """Greet someone with a customizable greeting."""
    print(f"{greeting}, {name}!")

greet("Alice")                # Hello, Alice!
greet("Bob", "Good morning")  # Good morning, Bob!

Problem 8: Calculate Average Medium

Write a function average(*numbers) that accepts any number of arguments and returns their average. Handle the case where no arguments are given.

Use *numbers to accept variable arguments. Check len(numbers) before dividing to avoid division by zero.
def average(*numbers):
    """Return the average of all arguments."""
    if len(numbers) == 0:
        return 0
    return sum(numbers) / len(numbers)

print(average(10, 20, 30))      # 20.0
print(average(100))              # 100.0
print(average())                 # 0

Problem 9: Return Multiple Values Medium

Write a function min_max(numbers) that takes a list of numbers and returns both the minimum and maximum as a tuple. Unpack the result.

Use return min(numbers), max(numbers). Unpack with low, high = min_max(my_list).
def min_max(numbers):
    """Return the min and max of a list."""
    return min(numbers), max(numbers)

low, high = min_max([3, 1, 4, 1, 5, 9])
print(f"Min: {low}, Max: {high}")
# Min: 1, Max: 9

Problem 10: Price Calculator Medium

Write a function calculate_price(amount, tax_rate=0.10, discount=0) that returns the final price after applying the discount and then adding tax. Test with keyword arguments.

First apply the discount: amount - discount. Then apply tax: discounted * (1 + tax_rate).
def calculate_price(amount, tax_rate=0.10, discount=0):
    """Calculate final price with tax and discount."""
    discounted = amount - discount
    final = discounted * (1 + tax_rate)
    return round(final, 2)

print(calculate_price(100))                        # 110.0
print(calculate_price(100, discount=20))             # 88.0
print(calculate_price(100, tax_rate=0.08, discount=10))  # 97.2

Problem 11: Scope Detective Medium

Predict the output of this code without running it, then verify:

x = 5

def change():
    x = 10
    print(f"Inside: {x}")

change()
print(f"Outside: {x}")
Inside: 10 Outside: 5

The assignment inside the function creates a local variable x. The global x is unchanged.

Problem 12: Build a Profile Hard

Write a function build_profile(first, last, **details) that returns a dictionary with the name and any extra keyword arguments as additional fields.

Create a dictionary with first and last name, then use .update(details) to add the extra keyword arguments.
def build_profile(first, last, **details):
    """Build a user profile dictionary."""
    profile = {"first_name": first, "last_name": last}
    profile.update(details)
    return profile

user = build_profile("Alice", "Smith", age=25, city="LA")
print(user)
# {'first_name': 'Alice', 'last_name': 'Smith', 'age': 25, 'city': 'LA'}

Problem 13: Factorial Hard

Write a function factorial(n) that returns the factorial of n (n! = n * (n-1) * ... * 1). Handle the edge case where n is 0 (0! = 1).

Use a loop that multiplies from 1 to n. Or use recursion: n * factorial(n - 1) with base case n == 0.
def factorial(n):
    """Return the factorial of n."""
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

print(factorial(0))   # 1
print(factorial(5))   # 120
print(factorial(10))  # 3628800

Problem 14: Apply a Function to a List Hard

Write a function apply_to_each(func, items) that takes a function and a list, applies the function to each item, and returns a new list of results. Test it with your square function.

Create an empty result list. Loop through items, call func(item) for each, and append to the result list.
def square(n):
    return n ** 2

def apply_to_each(func, items):
    """Apply func to each item and return results."""
    result = []
    for item in items:
        result.append(func(item))
    return result

numbers = [1, 2, 3, 4, 5]
squared = apply_to_each(square, numbers)
print(squared)  # [1, 4, 9, 16, 25]

Problem 15: Grade Calculator Hard

Write a function letter_grade(score) that returns the letter grade for a numeric score: A (90+), B (80-89), C (70-79), D (60-69), F (below 60). Then write a function class_report(names, scores) that takes two lists and prints a formatted report.

Use if/elif/else in letter_grade. In class_report, use zip(names, scores) to loop through both lists together.
def letter_grade(score):
    """Return the letter grade for a numeric score."""
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

def class_report(names, scores):
    """Print a formatted grade report."""
    print(f"{"Name":<15} {"Score":<8} {"Grade"}")
    print("-" * 30)
    for name, score in zip(names, scores):
        grade = letter_grade(score)
        print(f"{name:<15} {score:<8} {grade}")

names = ["Alice", "Bob", "Carol"]
scores = [95, 72, 88]
class_report(names, scores)
Take the Module 9 Quiz Back to Module 9