Python exercises
Every exercise checks your output automatically and has three hints before the solution. Stuck? Open the lesson it comes from.
What is Python?
Make Python print exactly two lines: I am learning Python and then the result of 7 * 6.
I am learning Python 42
From the lesson What is Python?
Your first program
Print a three-line greeting card: Happy birthday!, then an empty line, then From Python.
Happy birthday! From Python
From the lesson Your first program
Variables
Create city = "Brussels" and days = 3, then print exactly: 3 days in Brussels.
3 days in Brussels
From the lesson Variables
Numbers
A trip costs 250 euros and is split between 3 friends. Print each friend's share rounded to 2 decimals, then on a second line the whole euros each pays (no decimals), then the euros left over.
83.33 83 1
From the lesson Numbers
Strings
Clean up email = " Asha.Rao@Example.COM ": remove the spaces, make it lowercase, then print the cleaned email and, on a second line, only the part after the @.
asha.rao@example.com example.com
From the lesson Strings
Lists
Start with cart = ["milk", "bread"]. Add "eggs" at the end, put "coffee" at the front, remove "bread", then print the cart sorted alphabetically and, on a second line, how many items it has.
['coffee', 'eggs', 'milk'] 3
From the lesson Lists
Tuples and sets
Two teams worked on a project. team_a = ["ana", "raj", "li", "raj"] and team_b = ["li", "tom", "ana"]. Print, as sorted lists: everyone who worked on it (no duplicates), then the people in both teams.
['ana', 'li', 'raj', 'tom'] ['ana', 'li']
From the lesson Tuples and sets
Dictionaries
Count the votes in votes = ["python", "rust", "python", "go", "python", "go"] with a dictionary, then print each language and its count on its own line, like python: 3, in the order they first appear.
python: 3 rust: 1 go: 2
From the lesson Dictionaries
Conditions
Write grades for these scores: scores = [92, 75, 58, 81]. Print one line per score: A for 90 and above, B for 75–89, C for 60–74 and F below 60, formatted like 92: A.
92: A 75: B 58: F 81: B
From the lesson Conditions
Loops
Classic FizzBuzz: for the numbers 1 to 15, print FizzBuzz if the number divides by both 3 and 5, Fizz if it divides by 3, Buzz if it divides by 5, and otherwise the number itself — one per line.
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
From the lesson Loops
Functions
Write a function to_fahrenheit(celsius: float) -> float that returns celsius * 9 / 5 + 32. Then print the result for 0, 37 and -40, one per line.
32.0 98.6 -40.0
From the lesson Functions
Files and errors
Add up the valid numbers in values = ["10", "x", "5", "", "7"]. Use try / except ValueError to skip anything that isn't a whole number. Print the total, then on a second line how many values were skipped.
22 2
From the lesson Files and errors
Comprehensions
From temps = {"Mon": 12, "Tue": 19, "Wed": 23, "Thu": 17} print, with comprehensions: a list of the days warmer than 15 degrees, then a dict that maps each day to its temperature in Fahrenheit (c * 9 / 5 + 32).
['Tue', 'Wed', 'Thu']
{'Mon': 53.6, 'Tue': 66.2, 'Wed': 73.4, 'Thu': 62.6}From the lesson Comprehensions
Lambda, map, filter and reduce
Sort products = [("mug", 8.5), ("tea", 3.0), ("lamp", 24.0)] from most to least expensive and print the result. Then print only the names of products under 10, using any approach you like.
[('lamp', 24.0), ('mug', 8.5), ('tea', 3.0)]
['mug', 'tea']From the lesson Lambda, map, filter and reduce
Classes and objects
Write a class Counter with a count attribute starting at 0, a method increment(step=1) that adds to it, and a __repr__ that returns Counter(count=N). Create one, increment it once by default and once by 5, then print it.
Counter(count=6)
From the lesson Classes and objects
Dataclasses
Create a dataclass Book with title: str, pages: int and read: bool = False. Make a list of three books — Book("Dune", 412), Book("Atomic Habits", 320, True), Book("SPQR", 608) — then print the titles of unread books and, on a second line, their total pages.
['Dune', 'SPQR'] 1020
From the lesson Dataclasses
Modules, packages and environments
Use the standard library: import Counter from collections and mean from statistics. For rolls = [3, 6, 2, 6, 6, 1, 3], print the most common roll and how often it appears as a tuple, then the average roll rounded to 2 decimals.
(6, 3) 3.86
From the lesson Modules, packages and environments
Iterators and generators
Write a generator evens(limit) that yields the even numbers from 0 up to and including limit. Print list(evens(10)), then the sum of evens(100).
[0, 2, 4, 6, 8, 10] 2550
From the lesson Iterators and generators
Decorators
Write a decorator log_call that prints Calling NAME before running the function (use func.__name__) and then returns the function's result. Decorate def add(a, b): return a + b with it and print add(2, 3).
Calling add 5
From the lesson Decorators
Type hints
Write a fully type-hinted function average(values: list[float]) -> float | None that returns None for an empty list and the rounded (2 decimals) average otherwise. Print the result for [4.0, 5.5, 9.0] and for [].
6.17 None
From the lesson Type hints
Testing with pytest
Write is_palindrome(text: str) -> bool that ignores case and spaces, so "Never odd or even" is a palindrome. The starter includes plain assert tests; make them all pass so the program prints All tests passed.
All tests passed
From the lesson Testing with pytest
Project: build a dodge game with pygame
Write the game's move_player rule as a pure function: clamp_x(x, step, width, player_w) returns x + step but never less than 0 and never more than width - player_w. Print the results for (100, 7, 480, 50), (3, -7, 480, 50) and (428, 7, 480, 50).
107 0 430
From the lesson Project: build a dodge game with pygame
Concurrency vs parallelism
Write best_tool(task: str) -> str that returns "threads" for "download" and "api call", "processes" for "resize images" and "train model", and "sequential" for anything else. Print the result for each of: download, train model, add two numbers.
threads processes sequential
From the lesson Concurrency vs parallelism
Threads
Plan a thread pool. Write batches(items, size) that splits a list into lists of at most size items (the way a pool hands work to workers). Print batches(list(range(7)), 3) and then how many batches 100 URLs make with size=8.
[[0, 1, 2], [3, 4, 5], [6]] 13
From the lesson Threads
Multiprocessing
Prepare work for a process pool. Write a top-level function word_count(text: str) -> int, then use the built-in map (exactly like pool.map) to count words in docs = ["one two", "three four five", "six"]. Print the list of counts and their total.
[2, 3, 1] 6
From the lesson Multiprocessing
async and await
Estimate the gain from async. Given call durations durations = [1.2, 0.4, 0.9, 0.3] (seconds), print the total time if you await them one by one, then the time with gather (they overlap, so it's the slowest one). Round both to 1 decimal.
2.8 1.2
From the lesson async and await
Sockets and networking
Servers must parse what arrives. Write parse_request_line(line: str) that splits an HTTP request line such as "GET /learn/?page=2 HTTP/1.1" into method, path and version, and returns them as a tuple. Print the result, then just the path without the query string (the part before ?).
('GET', '/learn/?page=2', 'HTTP/1.1')
/learn/From the lesson Sockets and networking
Performance and profiling
Speed up this de-duplication. Write unique_in_order(items) that keeps the first occurrence of each item in its original order, using a set to remember what you've seen. Print the result for [3, 1, 3, 2, 1, 4], then the length of the result for list(range(50_000)) * 2.
[3, 1, 2, 4] 50000
From the lesson Performance and profiling
Packaging and publishing
Package tools compare versions as numbers, not text. Write parse_version(v: str) -> tuple[int, ...] that turns "3.15.0" into (3, 15, 0). Then print "3.9.1" < "3.15.0" as plain strings, the same comparison with your function, and the newest of ["0.9.0", "0.10.2", "0.10.10"] using max(..., key=parse_version).
False True 0.10.10
From the lesson Packaging and publishing
Project: speed up API calls
Compute free cash flow for the report. Given rows = [{"ticker": "NEM", "operations": 2870, "capex": 1570}, {"ticker": "FCX", "operations": 5160, "capex": 4810}, {"ticker": "BHP", "operations": 20670, "capex": 9270}], print each ticker with its free cash flow like NEM: 1300, then the ticker with the highest free cash flow.
NEM: 1300 FCX: 350 BHP: 11400 BHP
From the lesson Project: speed up API calls
NumPy essentials
Min-max scale exam scores to the range 0–1, a common step before training a model. With scores = np.array([50, 70, 90, 100]), compute (scores - min) / (max - min), then print the scaled array and the number of students above 0.5.
[0. 0.4 0.8 1. ] 2
From the lesson NumPy essentials
pandas for data analysis
For the orders below, add a total column (qty * unit_price), then print the total revenue per customer as a Series sorted from highest to lowest.
customer Ben 75.0 Ana 50.0 Cara 20.0 Name: total, dtype: float64
From the lesson pandas for data analysis
Charts with matplotlib
Prepare data for a chart. From sales = {"Mon": 120, "Tue": 95, "Wed": 140, "Thu": 80, "Fri": 160}, print the list of days and the list of values (the two inputs for ax.bar), then the day with the highest sales. Bonus: plot it with ax.bar(days, values) and press Run.
['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] [120, 95, 140, 80, 160] Fri
From the lesson Charts with matplotlib
Machine learning with scikit-learn
Compute accuracy by hand. With y_true = [0, 1, 1, 2, 2, 2, 0, 1] and y_pred = [0, 1, 2, 2, 2, 1, 0, 1], print how many predictions are correct, then the accuracy rounded to 3 decimals.
6 0.75
From the lesson Machine learning with scikit-learn
Calling LLM APIs from Python
Estimate cost before you call. Write estimate_cost(input_tokens, output_tokens, in_price, out_price) where prices are per million tokens, returning dollars. Print the cost of 12,000 input and 800 output tokens at $3 in / $15 out per million, rounded to 4 decimals, then the cost of 1,000 such calls rounded to 2 decimals.
0.048 48.0
From the lesson Calling LLM APIs from Python
RAG basics: answer questions from your documents
Build the simplest retriever: score each chunk by how many words of the question it contains (lowercase, split on spaces), and print the best chunk for the question "when do laptops get replaced".
laptops are replaced every three years
From the lesson RAG basics: answer questions from your documents
Build an AI API with FastAPI
Write the validation FastAPI would do, by hand. validate_question(data: dict) -> list[str] returns a list of error messages: "text is required" if the key is missing, "text is too short" if it has fewer than 3 characters, "text is too long" above 500. Print the result for {}, {"text": "hi"} and {"text": "What is RAG?"}.
['text is required'] ['text is too short'] []
From the lesson Build an AI API with FastAPI