Intermediate Python exercises, solved and explained (runnable in your browser)
You have the Python basics (variables, conditions, loops) and want to step up to intermediate level? These six exercises cover the tools that separate "knowing the syntax" from solving problems: functions, dictionaries, comprehensions and error handling. All runnable and editable here with "Try it".
Exercise 1 — A function that computes
Write a function that tells whether a year is a leap year.
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
print(is_leap(2024))
print(is_leap(1900))
print(is_leap(2000))A function that returns a value (return) is reusable and testable. Notice how the leap-year logic fits in one line of conditions.
Exercise 2 — A dictionary as an address book
Store contacts and look up a number.
book = {"Anna": "333-111", "Luca": "333-222"}
book["Marco"] = "333-333" # add
print(book["Luca"]) # look up
print("Sara" in book) # exists?A dictionary maps a key (the name) to a value (the number): instant lookup, no scanning a list. It is one of the most used structures ever.
Exercise 3 — List comprehension
From a list of numbers, keep only the squares of the even ones.
numbers = [1, 2, 3, 4, 5, 6]
even_squares = [n * n for n in numbers if n % 2 == 0]
print(even_squares)A comprehension builds a list in one line: "take n*n for each n in numbers, if n is even". It is the idiomatic (and readable) way to transform data in Python.
Exercise 4 — Counting frequencies
Count how many times each word appears.
words = ["bread", "milk", "bread", "coffee", "milk", "bread"]
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts).get(w, 0) returns the current value or 0 if the key is not there yet: the classic counting pattern. The result is a dictionary word → occurrences.
Exercise 5 — Filter and sort
From a list of people, keep the adults sorted by age.
people = [("Anna", 17), ("Luca", 25), ("Sara", 19)]
adults = [p for p in people if p[1] >= 18]
adults.sort(key=lambda p: p[1])
print(adults)key=lambda p: p[1] tells sort to order by the second element (age). lambdas are throwaway functions, very handy in exactly these cases.
Exercise 6 — Handling errors
Divide two numbers without crashing if the divisor is zero.
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
print(divide(10, 2))
print(divide(10, 0))try/except catches the error instead of blowing up the program: that is what makes code "robust". It separates a throwaway script from a real program.
What next?
If these went well, you are ready for the more interesting part of Python. The Python path continues with OOP, modules, files and guided projects, always with runnable practice in the browser. The first chapters are free; in the playground you can experiment freely.