Python Exercises

Practise what you've learned. Type the missing piece into each highlighted gap and press Check. Further down are coding problems to solve in the editor, each with a worked solution.

Fill in the blanks

Basics

Print a message.

("Hello, Python!")

Convert the text to an integer.

age = ("42")

Use floor division to get a whole-number result.

pages = 125  10  # 12

Insert the variable into an f-string.

greeting = "Hello, {name}!"

Format the price with exactly two decimal places.

print(f"Total: {price:}")

Remove whitespace from both ends of the string.

clean = raw.()

Reverse the string with a slice.

backwards = word[::]

Check whether a value is missing.

if result  None:
    print("nothing found")

Control flow

Complete the conditional chain.

if score >= 90:
    grade = "A"
 score >= 80:
    grade = "B"
else:
    grade = "C"

Loop five times, from 0 to 4.

for i in (5):
    print(i)

Get both the index and the item.

for i, name in (names):
    print(i, name)

Leave the loop early.

for n in numbers:
    if n < 0:
        

Match any value not handled by earlier cases.

match command:
    case "quit":
        stop()
    case :
        print("unknown")

Data structures

Add an item to the end of the list.

fruits.("mango")

Build a list of squares with a comprehension.

squares = [n * n  n in range(10)]

Create a tuple with a single item.

single = (42)

Remove duplicates by converting to a set.

unique = (visits)

Read a key with a default when it's missing.

port = config.("port", 8080)

Loop over keys and values together.

for key, value in prices.():
    print(key, value)

Count occurrences in one line.

from collections import Counter
counts = (words)

Functions

Define a function.

 area(width, height):
    return width * height

Accept any number of positional arguments.

def total(*):
    return sum(args)

Write a small anonymous function for the sort key.

people.sort(key= p: p["age"])

Annotate the return type.

def greet(name: str)  str:
    return f"Hi {name}"

Produce values lazily from a generator.

def countdown(n):
    while n > 0:
         n
        n -= 1

Classes, errors and files

Name the method that initialises a new object.

class Dog:
    def (self, name):
        self.name = name

Call the parent class's initialiser.

class Puppy(Dog):
    def __init__(self, name):
        ().__init__(name)

Generate __init__ and __repr__ automatically.

from dataclasses import dataclass

@
class Point:
    x: float
    y: float

Handle invalid input.

try:
    value = int(text)
 ValueError:
    value = 0

Signal an error from your own code.

if amount <= 0:
     ValueError("amount must be positive")

Open the file so it's closed automatically.

 open("notes.txt", encoding="utf-8") as f:
    content = f.read()

Parse a JSON string into Python data.

import json
data = json.(text)

Coding problems

1. Count vowels

Write count_vowels(text) that returns how many vowels (a, e, i, o, u, any case) the text contains.

Try it yourself
Console output
Show solution
PY solution.py
def count_vowels(text):
    return sum(1 for ch in text.lower() if ch in "aeiou")

print(count_vowels("Python Programming Is Fun"))
Output
6

2. Word frequency

Return the three most common words in a text, ignoring case and punctuation.

Try it yourself
Console output
Show solution
PY solution.py
import re
from collections import Counter

text = "The cat sat. The cat ran! A dog sat; the dog barked."

def top_words(text, n=3):
    words = re.findall(r"[a-z]+", text.lower())
    return Counter(words).most_common(n)

print(top_words(text))
Output
[('the', 3), ('cat', 2), ('sat', 2)]

3. Group anagrams

Group words that are anagrams of each other (same letters, different order).

Try it yourself
Console output
Show solution
PY solution.py
from collections import defaultdict

words = ["listen", "silent", "enlist", "google", "gooegl", "cat", "act"]

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return list(groups.values())

print(group_anagrams(words))
Output
[['listen', 'silent', 'enlist'], ['google', 'gooegl'], ['cat', 'act']]

Sorting a word's letters gives the same "signature" for every anagram, which works as a dictionary key.

4. Flatten nested lists

Write a recursive function that flattens arbitrarily nested lists.

Try it yourself
Console output
Show solution
PY solution.py
def flatten(items):
    result = []
    for item in items:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result

print(flatten([1, [2, [3, [4, 5]], 6], [], 7]))
Output
[1, 2, 3, 4, 5, 6, 7]

5. A bank account class

Create an Account class with deposit and withdraw methods that raise ValueError for invalid amounts or insufficient funds, and a read-only balance property.

Try it yourself
Console output
Show solution
PY solution.py
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance

    @property
    def balance(self):
        return self._balance

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

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("withdrawal must be positive")
        if amount > self._balance:
            raise ValueError("insufficient funds")
        self._balance -= amount

acc = Account("Ana", 100)
acc.deposit(50)
acc.withdraw(30)
print(acc.balance)
try:
    acc.withdraw(500)
except ValueError as err:
    print("Error:", err)
Output
120
Error: insufficient funds

6. Validate and summarise records

Given rows of "name,score" text, skip invalid rows and return the average of the valid scores along with the list of rejected rows.

Try it yourself
Console output
Show solution
PY solution.py
rows = ["ana,91", "ben,abc", "cleo,85", "dev", "eli,78"]

def summarise(rows):
    scores, rejected = [], []
    for row in rows:
        try:
            _, score = row.split(",")
            scores.append(int(score))
        except ValueError:
            rejected.append(row)
    average = round(sum(scores) / len(scores), 1) if scores else 0
    return average, rejected

print(summarise(rows))
Output
(84.7, ['ben,abc', 'dev'])

One except ValueError covers both kinds of bad row: a missing comma (unpacking fails) and a non-numeric score (int() fails).