Skip to content
Tutorials Center
My learning

Topics

Lesson 147 of 149 ยท Practice and Review

Python Practice Exercises

27 graded Python exercises with solutions on strings, loops, dictionaries, functions, files, classes, generators and algorithms. Run them in your browser.

Reading about code and writing code are different skills, and only practice builds the second one. This page collects 27 exercises that cover the whole course, grouped by topic and ordered from beginner to advanced. Each one has a short task, an editor with starter code, and a hidden solution.

Here's how to get the most out of them:

  • Try first, peek later. Give each exercise an honest attempt before opening the solution. Getting stuck for a few minutes is where the learning happens.
  • Run often. Each starter prints test calls, so you can see when your output matches the expected result in the comments.
  • Compare, don't copy. Your solution may look different from ours and still be correct. Read ours for ideas, then improve your own.

Every exercise group links to the lesson it practices, and the cheat sheet is handy to keep open in another tab. Exercises that use input() come with preset answers in the editor's Input box, which you can change to test other values.

Strings and basics

These practice variables, input and output, strings, string methods and string formatting.

1. Birthday greeting (Beginner)

Read a name and an age with input(), then print a line like Hi Mina! Next year you'll be 28. Remember that input() always returns a string.

Python Exercise 1: Birthday greeting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
name = input("Name: ")
age = int(input("Age: "))

print(f"Hi {name}! Next year you'll be {age + 1}.")

Converting with int() is the key step: adding 1 to the string "27" would raise a TypeError.

2. Conversion table (Beginner)

Print a table of Celsius temperatures from 0 to 100 in steps of 20 with their Fahrenheit values (F = C * 9 / 5 + 32). Align the columns and show one decimal place for Fahrenheit.

Python Exercise 2: Conversion table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
print("   C        F")
for celsius in range(0, 101, 20):
    fahrenheit = celsius * 9 / 5 + 32
    print(f"{celsius:>4} {fahrenheit:>8.1f}")

range(0, 101, 20) includes 100 because the stop value is excluded, and the format specs >4 and >8.1f right-align each column.

3. Palindrome checker (Beginner)

Write is_palindrome(text) that returns True if the text reads the same backward, ignoring case, spaces and punctuation.

Python Exercise 3: Palindromes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def is_palindrome(text: str) -> bool:
    letters = [char.lower() for char in text if char.isalnum()]
    return letters == letters[::-1]

Keeping only alphanumeric characters removes spaces and punctuation, and [::-1] gives a reversed copy to compare against.

4. Vowel counter (Beginner)

Write count_vowels(text) that returns a dictionary with how many times each vowel (a, e, i, o, u) appears, ignoring case. Include vowels that appear zero times.

Python Exercise 4: Vowel counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def count_vowels(text: str) -> dict[str, int]:
    lowered = text.lower()
    return {vowel: lowered.count(vowel) for vowel in "aeiou"}

A dict comprehension over "aeiou" guarantees every vowel appears as a key, and str.count() does the counting.

Control flow

Practice for if statements, for loops, while loops and break and continue.

5. Tick-Tock (Beginner)

For the numbers 1 to 20, print Tick for multiples of 3, Tock for multiples of 5, TickTock for multiples of both, and the number itself otherwise.

Python Exercise 5: Tick-Tock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
for n in range(1, 21):
    word = ""
    if n % 3 == 0:
        word += "Tick"
    if n % 5 == 0:
        word += "Tock"
    print(word or n)

Building the word in two independent if checks handles "both" automatically, and word or n falls back to the number when the word is empty.

6. Leap years (Beginner)

A year is a leap year if it's divisible by 4, except years divisible by 100, unless they're also divisible by 400. Write is_leap(year).

Python Exercise 6: Leap years

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def is_leap(year: int) -> bool:
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

The parentheses group the exception and its exception. In real code, calendar.isleap(year) does the same job.

7. Digital root (Intermediate)

Add up the digits of a number. If the result has more than one digit, repeat until a single digit remains. For 98,765: 9+8+7+6+5 = 35, then 3+5 = 8.

Python Exercise 7: Digital root

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def digital_root(number: int) -> int:
    while number >= 10:
        number = sum(int(digit) for digit in str(number))
    return number

The while loop repeats exactly as long as there's more than one digit; converting to a string is the simplest way to visit the digits.

8. Guess the number (Intermediate)

The secret number is 37. Keep asking for guesses, answer Too low or Too high, and when the guess is right, print how many attempts it took. The Input box already contains three guesses.

Python Exercise 8: Guess the number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
secret = 37
attempts = 0

while True:
    guess = int(input("Guess: "))
    attempts += 1
    if guess < secret:
        print("Too low")
    elif guess > secret:
        print("Too high")
    else:
        print(f"Correct! You needed {attempts} attempts.")
        break

while True with break fits loops whose exit condition is found in the middle. The number guessing project builds a full version.

Lists, dictionaries and sets

Practice for lists, list methods, dictionaries, sets, comprehensions and collections.

9. Second largest (Beginner)

Return the second largest distinct value in a list, or None if there isn't one.

Python Exercise 9: Second largest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def second_largest(numbers: list[int]) -> int | None:
    unique = sorted(set(numbers), reverse=True)
    return unique[1] if len(unique) >= 2 else None

A set removes the duplicate 9s, so the second item of the sorted result is the answer. For huge lists, a single pass that tracks the top two values avoids sorting.

10. Remove duplicates, keep order (Beginner)

Return a new list without duplicates, keeping the first occurrence of each value in its original position.

Python Exercise 10: Unique in order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def unique(items: list) -> list:
    return list(dict.fromkeys(items))

Dictionaries keep insertion order and can't have duplicate keys, so dict.fromkeys() is a one-line order-preserving dedupe. A loop with a seen set works too.

11. Top words (Intermediate)

Return the n most common words in a text as (word, count) pairs. Ignore case and strip the punctuation .,!? from each word.

Python Exercise 11: Top words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from collections import Counter

def top_words(text: str, n: int) -> list[tuple[str, int]]:
    words = (word.strip(".,!?").lower() for word in text.split())
    return Counter(words).most_common(n)

Counter.most_common() sorts by count, and ties keep the order in which words were first seen, which is why cat comes before sat.

12. Group by value (Intermediate)

Given a dictionary of people and their cities, build a dictionary that maps each city to a sorted list of people.

Python Exercise 12: Group by city

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from collections import defaultdict

def by_city(people: dict[str, str]) -> dict[str, list[str]]:
    groups = defaultdict(list)
    for person, city in people.items():
        groups[city].append(person)
    return {city: sorted(names) for city, names in groups.items()}

defaultdict(list) creates each list on first use, and the final comprehension sorts the names and returns a plain dictionary.

13. Transpose a matrix (Intermediate)

Turn rows into columns: [[1, 2, 3], [4, 5, 6]] becomes [[1, 4], [2, 5], [3, 6]]. Try it with a comprehension, then with zip().

Python Exercise 13: Transpose

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def transpose(matrix: list[list[int]]) -> list[list[int]]:
    return [[row[col] for row in matrix] for col in range(len(matrix[0]))]

def transpose_zip(matrix: list[list[int]]) -> list[list[int]]:
    return [list(column) for column in zip(*matrix)]

zip(*matrix) unpacks the rows as separate arguments, so zip pairs up the first items, then the second items, and so on.

Functions

Practice for functions, arguments, recursion, higher-order functions and decorators.

14. Flexible average (Beginner)

Write average(*numbers) that accepts any number of arguments and returns their mean. Raise a ValueError with a helpful message when called with no numbers.

Python Exercise 14: Flexible average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def average(*numbers: float) -> float:
    if not numbers:
        raise ValueError("average() needs at least one number")
    return sum(numbers) / len(numbers)

*numbers collects the arguments into a tuple, and an empty tuple is falsy, which makes the check short.

15. Deep sum (Intermediate)

Add up every number in a list that can contain nested lists at any depth.

Python Exercise 15: Deep sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def deep_sum(items: list) -> int:
    total = 0
    for item in items:
        if isinstance(item, list):
            total += deep_sum(item)
        else:
            total += item
    return total

The function calls itself for every nested list, and the base case is simply a plain number. This is the classic shape of a recursive solution.

16. Staircase climber (Advanced)

You can climb a staircase 1 or 2 steps at a time. Write ways(n) that returns how many different ways there are to reach step n. Make it fast enough for n = 90.

Python Exercise 16: Staircase climber

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from functools import cache

@cache
def ways(n: int) -> int:
    if n <= 1:
        return 1
    return ways(n - 1) + ways(n - 2)

The last move is either 1 or 2 steps, so the answer is the sum of the two smaller problems. Without @cache the same values would be recomputed billions of times.

17. Call counter decorator (Advanced)

Write a decorator counted that counts how many times a function is called and stores the number in a calls attribute on the wrapper.

Python Exercise 17: Call counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from functools import wraps

def counted(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        return func(*args, **kwargs)
    wrapper.calls = 0
    return wrapper

Functions are objects, so the wrapper can carry its own attribute. @wraps copies the original name and docstring onto the wrapper.

Errors and files

Practice for exceptions, raising exceptions, files and CSV files.

18. Safe conversion (Beginner)

Write to_int(text, default=0) that converts text to an integer, or returns the default when the text isn't a valid number.

Python Exercise 18: Safe conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def to_int(text: str, default: int = 0) -> int:
    try:
        return int(text)
    except ValueError:
        return default

Catch only ValueError, the error int() raises for bad text, so real bugs such as passing None still show up.

19. Ask until valid (Intermediate)

Keep asking for a positive whole number. For text that isn't a number, print Not a number; for zero or negatives, print Must be positive. Print the accepted value at the end.

Python Exercise 19: Ask until valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
while True:
    text = input("Positive number: ")
    try:
        value = int(text)
    except ValueError:
        print("Not a number")
        continue
    if value <= 0:
        print("Must be positive")
        continue
    break

print("Accepted:", value)

Each problem gets its own message and continue; only valid input reaches break. Wrapping this in a function makes it reusable.

20. CSV averages (Intermediate)

Write the given rows to scores.csv, then read the file back and print each student's average with one decimal place.

Python Exercise 20: CSV averages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import csv

rows = [
    ["name", "quiz1", "quiz2", "quiz3"],
    ["Ana", "8", "9", "10"],
    ["Ben", "6", "7", "5"],
]

with open("scores.csv", "w", newline="", encoding="utf-8") as file:
    csv.writer(file).writerows(rows)

with open("scores.csv", newline="", encoding="utf-8") as file:
    for row in csv.DictReader(file):
        marks = [int(value) for key, value in row.items() if key != "name"]
        print(f"{row['name']}: {sum(marks) / len(marks):.1f}")

CSV values are always strings, so convert them before doing math, and open CSV files with newline="".

Classes and objects

Practice for classes, special methods, custom exceptions and data classes.

21. Bank account (Intermediate)

Create a BankAccount class with deposit() and withdraw(). Both reject amounts that aren't positive with a ValueError, and withdraw() raises an InsufficientFunds exception when the balance is too low. Expose balance as a read-only property.

Python Exercise 21: Bank account

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
class InsufficientFunds(Exception):
    pass

class BankAccount:
    def __init__(self, owner: str, balance: float = 0) -> None:
        self.owner = owner
        self._balance = balance

    @property
    def balance(self) -> float:
        return self._balance

    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self._balance += amount

    def withdraw(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("withdrawal must be positive")
        if amount > self._balance:
            raise InsufficientFunds(f"balance is only {self._balance}")
        self._balance -= amount

The property has no setter, so account.balance = 1_000_000 raises an AttributeError; the only way to change the balance is through the validated methods.

22. A Vector type (Intermediate)

Write a Vector class for 2-D vectors that supports +, * with a number, ==, abs() (the length) and a readable repr.

Python Exercise 22: Vector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import math

class Vector:
    def __init__(self, x: float, y: float) -> None:
        self.x = x
        self.y = y

    def __add__(self, other: "Vector") -> "Vector":
        return Vector(self.x + other.x, self.y + other.y)

    def __mul__(self, factor: float) -> "Vector":
        return Vector(self.x * factor, self.y * factor)

    def __eq__(self, other: object) -> bool:
        return isinstance(other, Vector) and (self.x, self.y) == (other.x, other.y)

    def __abs__(self) -> float:
        return math.hypot(self.x, self.y)

    def __repr__(self) -> str:
        return f"Vector({self.x}, {self.y})"

Each operator maps to a special method. Add __rmul__ = __mul__ if you also want 2 * a to work.

23. Inventory report (Intermediate)

Use a data class Item with name, price and quantity, plus a value property (price times quantity). Print the items from the most to the least valuable stock.

Python Exercise 23: Inventory report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from dataclasses import dataclass

@dataclass
class Item:
    name: str
    price: float
    quantity: int

    @property
    def value(self) -> float:
        return self.price * self.quantity

stock = [Item("Lamp", 24.5, 10), Item("Desk", 240.0, 2), Item("Pen", 1.2, 300)]
for item in sorted(stock, key=lambda i: i.value, reverse=True):
    print(f"{item.name:<6}{item.value:>8.2f}")

The data class writes __init__ and __repr__ for you; a property keeps value always in sync with price and quantity.

Advanced challenges

Practice for generators, data structures and algorithms.

24. Fibonacci generator (Intermediate)

Write a generator fibonacci() that yields Fibonacci numbers forever (0, 1, 1, 2, 3, 5, ...). Use itertools.islice to print the first 12.

Python Exercise 24: Fibonacci generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
from itertools import islice

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

print(list(islice(fibonacci(), 12)))

An infinite generator is fine because values are produced one at a time, only when asked for. islice stops after 12.

25. Run-length encoding (Advanced)

Compress repeated characters: "aaabccdddd" becomes "3a1b2c4d". Then write decode() to reverse it (counts can have several digits).

Python Exercise 25: Run-length encoding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import re
from itertools import groupby

def encode(text: str) -> str:
    return "".join(f"{len(list(group))}{char}" for char, group in groupby(text))

def decode(code: str) -> str:
    return "".join(char * int(count) for count, char in re.findall(r"(\d+)(\D)", code))

itertools.groupby groups consecutive equal characters, and a regular expression splits the code into (count, character) pairs.

26. Binary search with insert position (Advanced)

Write search(items, target) for a sorted list. Return the index of target if present; otherwise return the index where it should be inserted to keep the list sorted. Don't use bisect; make it O(log n).

Python Exercise 26: Search or insert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
def search(items: list[int], target: int) -> int:
    low, high = 0, len(items)
    while low < high:
        middle = (low + high) // 2
        if items[middle] < target:
            low = middle + 1
        else:
            high = middle
    return low

This "half-open" version (high = len(items) and low < high) always ends at the first position whose value is at least target, which is exactly what bisect_left returns.

27. Postfix calculator (Advanced)

Evaluate expressions in postfix notation, where operators come after their operands: "3 4 + 2 *" means (3 + 4) * 2. Use a stack. Raise a ValueError for malformed input.

Python Exercise 27: Postfix calculator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import operator

OPERATORS = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv}

def evaluate(expression: str) -> float:
    stack: list[float] = []
    for token in expression.split():
        if token in OPERATORS:
            if len(stack) < 2:
                raise ValueError(f"not enough operands for {token!r}")
            right = stack.pop()
            left = stack.pop()
            stack.append(OPERATORS[token](left, right))
        else:
            stack.append(float(token))
    if len(stack) != 1:
        raise ValueError("expression must leave exactly one value")
    return stack[0]

Numbers are pushed; each operator pops two values (the right operand comes off first) and pushes the result. A dictionary of functions from operator replaces a long if/elif chain.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. In exercise 10, why does list(dict.fromkeys(items)) keep the original order?

    Since Python 3.7, dicts preserve insertion order, so the first occurrence of each value decides its position.
  2. 2. What makes the staircase solution in exercise 16 fast enough for n = 90?

    Without caching, the same subproblems are recomputed an exponential number of times.
  3. 3. In the postfix calculator, why is the first popped value used as the right operand?

    For "10 4 /", 4 is pushed after 10, so it comes off first and must be the divisor.

Summary

  • You practiced 27 problems across strings, control flow, collections, functions, errors, files, classes and algorithms.
  • Revisit any group whose exercises felt hard, and reread the linked lesson before trying again.
  • Try writing a second, different solution for exercises you solved: a loop instead of a comprehension, or the reverse.

Next: Python Interview Questions, common questions with concise answers to test how well you can explain what you know.