Learn Without Walls
← Back to Module 12

Module 12: Practice Problems

15 problems to practice error handling and debugging

Problem 1 Easy

What type of error would this code produce? print("Hello" + 5)

Think about what happens when you try to combine different data types.

TypeError - you cannot concatenate a string and an integer. Fix: print("Hello" + str(5)) or print(f"Hello{5}")

Problem 2 Easy

Write a try/except block that catches a ValueError when converting user input to an integer.

Put int(input(...)) in the try block and catch ValueError.

try:
    num = int(input("Enter a number: "))
    print(f"You entered {num}")
except ValueError:
    print("That's not a valid number!")

Problem 3 Easy

What type of error would my_list = [1, 2, 3]; print(my_list[5]) produce?

The list only has indices 0, 1, and 2.

IndexError: list index out of range - the list has 3 items (indices 0-2) but you tried to access index 5.

Problem 4 Easy

Write a try/except block that handles a ZeroDivisionError when dividing two numbers.

Put the division in the try block and catch ZeroDivisionError.

a = 10
b = 0
try:
    result = a / b
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Cannot divide by zero!")

Problem 5 Easy

What type of error would pritn("hello") produce?

Look carefully at the function name.

NameError: name 'pritn' is not defined - it is a typo of print.

Problem 6 Medium

Write a try/except/else block. Try to open a file for reading. If FileNotFoundError occurs, print an error. If successful, print the content.

The else block runs only when no error occurs in the try block.

try:
    file = open("data.txt", "r")
except FileNotFoundError:
    print("File not found!")
else:
    content = file.read()
    print(content)
    file.close()

Problem 7 Medium

Write a function safe_divide(a, b) that returns the result of a/b, but returns None if b is zero (using try/except).

Catch ZeroDivisionError and return None in the except block.

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print("Cannot divide by zero!")
        return None

print(safe_divide(10, 3))   # 3.333...
print(safe_divide(10, 0))   # None

Problem 8 Medium

Write a function that validates an email address. It should raise a ValueError if the email does not contain "@".

Use if "@" not in email: and then raise ValueError(...).

def validate_email(email):
    if "@" not in email:
        raise ValueError(f"Invalid email: {email} (missing @)")
    return True

try:
    validate_email("user@example.com")  # OK
    validate_email("invalid-email")     # Raises error
except ValueError as e:
    print(e)

Problem 9 Medium

Write code that catches multiple exception types. Ask for two numbers and divide them. Handle both ValueError (nonnumeric input) and ZeroDivisionError.

Use multiple except blocks, one for each error type.

try:
    a = float(input("Enter first number: "))
    b = float(input("Enter second number: "))
    result = a / b
    print(f"Result: {result}")
except ValueError:
    print("Please enter valid numbers!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

Problem 10 Medium

Add print debugging to this buggy function. The function should return the sum of even numbers in a list, but it returns the wrong value.

def sum_evens(numbers):
    total = 0
    for n in numbers:
        if n % 2 == 0:
            total = n    # Bug here
    return total

Add print statements to see what total is after each iteration.

def sum_evens(numbers):
    total = 0
    for n in numbers:
        if n % 2 == 0:
            print(f"DEBUG: n={n}, total before={total}")
            total += n   # Fix: += instead of =
            print(f"DEBUG: total after={total}")
    return total

# The bug was using = instead of +=
print(sum_evens([1, 2, 3, 4, 6]))  # Should be 12

Problem 11 Medium

Write a try/except/finally block that opens a file, reads it, and ensures the file is always closed in the finally block.

Declare file = None before the try block so it exists in the finally block even if open fails.

file = None
try:
    file = open("data.txt", "r")
    content = file.read()
    print(content)
except FileNotFoundError:
    print("File not found!")
finally:
    if file is not None:
        file.close()
        print("File closed.")

Problem 12 Hard

Write a function get_integer(prompt) that keeps asking the user for input until they enter a valid integer. Use a while loop with try/except.

Use while True and return to exit the loop when valid input is received.

def get_integer(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter a valid integer.")

age = get_integer("Enter your age: ")
print(f"Your age is {age}")

Problem 13 Hard

Write a function that safely accesses a dictionary key. If the key does not exist, catch the KeyError and return a default value.

Use try/except KeyError, or compare with the built in .get() method.

def safe_get(dictionary, key, default=None):
    try:
        return dictionary[key]
    except KeyError:
        return default

person = {"name": "Alice", "age": 30}
print(safe_get(person, "name"))           # Alice
print(safe_get(person, "email", "N/A"))  # N/A

Problem 14 Hard

Write a function process_scores(filename) that reads scores from a file, handles FileNotFoundError and ValueError, and returns the average score.

Use nested try/except - one for file operations, another for converting each line to a number.

def process_scores(filename):
    try:
        with open(filename, "r") as file:
            scores = []
            for line in file:
                try:
                    score = float(line.strip())
                    scores.append(score)
                except ValueError:
                    print(f"Skipping invalid: {line.strip()}")
            if scores:
                return sum(scores) / len(scores)
            return 0
    except FileNotFoundError:
        print(f"File '{filename}' not found!")
        return None

Problem 15 Hard

Find and fix all the bugs in this code. There are at least 4 errors.

def calculate_stats(numbers)
    if len(numbers) = 0:
        return None

    total = 0
    for num in numbers:
        total += num
    average = total / len(numbers)

    return "Average: " + average

print(calculate_stats([10, 20, 30]))

Look for: missing colon, wrong comparison operator, type mismatch in concatenation, and a possible indentation issue.

Bugs found:

  1. Missing : after function definition
  2. = should be == in the if condition
  3. Cannot concatenate string and float - need str(average) or f string
def calculate_stats(numbers):       # Fix 1: added :
    if len(numbers) == 0:            # Fix 2: = → ==
        return None

    total = 0
    for num in numbers:
        total += num
    average = total / len(numbers)

    return f"Average: {average}"     # Fix 3: use f-string

print(calculate_stats([10, 20, 30]))  # Average: 20.0