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!")
print() displays values (lesson 13).
Convert the text to an integer.
age = ("42")
int() converts strings to whole numbers (lesson 07).
Use floor division to get a whole-number result.
pages = 125 10 # 12
// divides and rounds down (lesson 12).
Insert the variable into an f-string.
greeting = "Hello, {name}!"
The f prefix enables {} placeholders (lesson 10).
Format the price with exactly two decimal places.
print(f"Total: {price:}")
.2f means fixed-point with 2 decimals (lesson 10).
Remove whitespace from both ends of the string.
clean = raw.()
strip() removes leading and trailing whitespace (lesson 09).
Reverse the string with a slice.
backwards = word[::]
A step of -1 walks backwards (lesson 08).
Check whether a value is missing.
if result None:
print("nothing found")
Always compare with None using is (lesson 11).
Control flow
Complete the conditional chain.
if score >= 90:
grade = "A"
score >= 80:
grade = "B"
else:
grade = "C"
elif means "else if" (lesson 14).
Loop five times, from 0 to 4.
for i in (5):
print(i)
range(5) produces 0, 1, 2, 3, 4 (lesson 17).
Get both the index and the item.
for i, name in (names):
print(i, name)
enumerate pairs each item with its position (lesson 17).
Leave the loop early.
for n in numbers:
if n < 0:
break exits the loop immediately (lesson 18).
Match any value not handled by earlier cases.
match command:
case "quit":
stop()
case :
print("unknown")
_ is the wildcard pattern (lesson 15).
Data structures
Add an item to the end of the list.
fruits.("mango")
append adds one item to the end (lesson 20).
Build a list of squares with a comprehension.
squares = [n * n n in range(10)]
Expression first, then the loop (lesson 21).
Create a tuple with a single item.
single = (42)
The comma makes a tuple (lesson 22).
Remove duplicates by converting to a set.
unique = (visits)
Sets keep only unique values (lesson 23).
Read a key with a default when it's missing.
port = config.("port", 8080)
get never raises KeyError (lesson 24).
Loop over keys and values together.
for key, value in prices.():
print(key, value)
.items() yields (key, value) pairs (lesson 24).
Count occurrences in one line.
from collections import Counter counts = (words)
Counter counts hashable items (lesson 27).
Functions
Define a function.
area(width, height):
return width * height
def starts a function definition (lesson 28).
Accept any number of positional arguments.
def total(*):
return sum(args)
*args collects extra positional arguments in a tuple (lesson 29).
Write a small anonymous function for the sort key.
people.sort(key= p: p["age"])
lambda params: expression (lesson 31).
Annotate the return type.
def greet(name: str) str:
return f"Hi {name}"
Return types follow -> (lesson 33).
Produce values lazily from a generator.
def countdown(n):
while n > 0:
n
n -= 1
yield turns a function into a generator (lesson 35).
Classes, errors and files
Name the method that initialises a new object.
class Dog:
def (self, name):
self.name = name
__init__ runs when an object is created (lesson 36).
Call the parent class's initialiser.
class Puppy(Dog):
def __init__(self, name):
().__init__(name)
super() reaches the parent class (lesson 37).
Generate __init__ and __repr__ automatically.
from dataclasses import dataclass
@
class Point:
x: float
y: float
Dataclasses remove boilerplate (lesson 40).
Handle invalid input.
try:
value = int(text)
ValueError:
value = 0
except catches the named exception (lesson 41).
Signal an error from your own code.
if amount <= 0:
ValueError("amount must be positive")
raise throws an exception (lesson 42).
Open the file so it's closed automatically.
open("notes.txt", encoding="utf-8") as f:
content = f.read()
with closes the file even if an error occurs (lesson 43).
Parse a JSON string into Python data.
import json data = json.(text)
loads parses a string; load reads a file (lesson 45).
Coding problems
1. Count vowels
Write count_vowels(text) that returns how many vowels (a, e, i, o, u, any case) the text contains.
Show solution
def count_vowels(text): return sum(1 for ch in text.lower() if ch in "aeiou") print(count_vowels("Python Programming Is Fun"))
6
2. Word frequency
Return the three most common words in a text, ignoring case and punctuation.
Show solution
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))
[('the', 3), ('cat', 2), ('sat', 2)]3. Group anagrams
Group words that are anagrams of each other (same letters, different order).
Show solution
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))
[['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.
Show solution
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]))
[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.
Show solution
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)
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.
Show solution
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))
(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).