Exercises with automatic checking

Write a solution and press “Check”. The code runs in the browser and goes through hidden tests. If a test fails, you will see what it checked, what was expected and what came out. Stuck? Open a hint. Solved exercises are remembered in this browser.

Schoolgirls in a typing class, around 1945

Your result

The first check loads Python: about 5 MB, which takes a few seconds.

0 of 40 exercises solved

Python basics

Functions, strings and dictionaries: every request handler is built on them.

1. Greeting

Level: Easy

Write a function greet(name) that returns the string Hello, Name!. Extra spaces around the name must be removed. If the name is empty, return Hello, guest!.

Show solution
def greet(name):
    name = name.strip()
    return f"Hello, {name or 'guest'}!"

2. Word count

Level: Easy

Write count_words(text): return a dictionary where the key is a word in lower case and the value is how many times it appears.

Show solution
def count_words(text):
    counts = {}
    for word in text.lower().split():
        counts[word] = counts.get(word, 0) + 1
    return counts

3. Strong password

Level: Easy

Write is_strong(password). A password is strong if it has at least 8 characters, at least one digit and at least one letter. Return True or False.

Show solution
def is_strong(password):
    has_digit = any(ch.isdigit() for ch in password)
    has_letter = any(ch.isalpha() for ch in password)
    return len(password) >= 8 and has_digit and has_letter

4. An address from a title

Level: Medium

Websites turn an article title into part of the address: My First Site → my-first-site. Write slugify(title) for Latin letters: keep letters and digits in lower case and replace everything else with a hyphen. Merge several hyphens in a row into one and remove hyphens at the ends.

Show solution
def slugify(title):
    chars = [ch if ch.isalnum() else "-" for ch in title.lower()]
    parts = "".join(chars).split("-")
    return "-".join(part for part in parts if part)

5. Shopping total

Level: Easy

Write total(prices): the function takes a list of prices and returns their sum. For an empty list return 0.

Show solution
def total(prices):
    result = 0
    for price in prices:
        result += price
    return result

6. Even numbers only

Level: Easy

Write only_even(numbers): return a new list that keeps only the even numbers, in the same order.

Show solution
def only_even(numbers):
    return [n for n in numbers if n % 2 == 0]

7. Short teaser

Level: Easy

Write truncate(text, limit). If the text is no longer than limit characters, return it unchanged. Otherwise return the first limit characters followed by three dots ....

Show solution
def truncate(text, limit):
    if len(text) <= limit:
        return text
    return text[:limit] + "..."

8. Longest word

Level: Medium

Write longest(words): return the longest word in the list. If there are several, return the first one. For an empty list return an empty string.

Show solution
def longest(words):
    best = ""
    for word in words:
        if len(word) > len(best):
            best = word
    return best

9. No duplicates

Level: Medium

Write unique(items): return the list without duplicates. The order of first appearances must be kept.

Show solution
def unique(items):
    result = []
    for item in items:
        if item not in result:
            result.append(item)
    return result

10. Initials

Level: Medium

Write initials(full_name): turn a first and last name into initials. Aru Bekova must become A. B. Make the letters capital and ignore extra spaces.

Show solution
def initials(full_name):
    parts = full_name.split()
    return " ".join(part[0].upper() + "." for part in parts)

HTTP and routes

What a framework does for you is easy to write in a simple form.

11. Parsing an address

Level: Medium

Write parse_query(query). It turns the string a=1&b=2 into the dictionary {"a": "1", "b": "2"}. Skip parts without an = sign. A value may contain =.

Show solution
def parse_query(query):
    result = {}
    for part in query.split("&"):
        if "=" in part:
            key, value = part.split("=", 1)
            result[key] = value
    return result

12. A simple router

Level: Medium

Finish handle(method, path). It looks up a handler in the ROUTES dictionary and returns a “code, text” pair. If there is no such address, return (404, "Not Found"). If the address exists but the method does not match, return (405, "Method Not Allowed").

Show solution
ROUTES = {
    "/": {"GET": "Home"},
    "/tasks": {"GET": "Task list", "POST": "Task created"},
}

def handle(method, path):
    if path not in ROUTES:
        return 404, "Not Found"
    if method not in ROUTES[path]:
        return 405, "Method Not Allowed"
    return 200, ROUTES[path][method]

13. Checking form data

Level: Hard

Write validate_user(data). The function takes a dictionary and returns a list of errors. The name field is required, and age must be a whole number from 1 to 120. Error texts: "name" and "age". If everything is correct, return an empty list.

Show solution
def validate_user(data):
    errors = []
    if not str(data.get("name", "")).strip():
        errors.append("name")
    age = data.get("age")
    if not isinstance(age, int) or isinstance(age, bool) or not 1 <= age <= 120:
        errors.append("age")
    return errors

14. A JSON response

Level: Medium

Write tasks_json(tasks). The function takes a list of dictionaries and returns a JSON string with only the tasks whose done is False. Non-English letters (like é) must stay readable. The import is already there.

Show solution
import json

def tasks_json(tasks):
    active = [task for task in tasks if not task["done"]]
    return json.dumps(active, ensure_ascii=False)

15. Your own template

Level: Medium

A template is text with gaps. Write render(template, data): it replaces every gap {{ name }} with the value from the data dictionary. There may or may not be spaces inside the braces. If the key is not in the dictionary, put an empty string.

Show solution
import re

def render(template, data):
    def value(match):
        return str(data.get(match.group(1), ""))
    return re.sub(r"\{\{\s*(\w+)\s*\}\}", value, template)

16. Pages of a list

Level: Medium

A long list is shown in parts. Write paginate(items, page, per_page): return the items of page number page (numbering starts at 1). If there is no page with that number, or the number is less than 1, return an empty list.

Show solution
def paginate(items, page, per_page):
    if page < 1:
        return []
    start = (page - 1) * per_page
    return items[start:start + per_page]

17. Status text

Level: Easy

Write status_text(code): return the name of a response code. 200 is OK, 201 is Created, 404 is Not Found, 500 is Internal Server Error. For any other code return Unknown.

Show solution
def status_text(code):
    names = {200: "OK", 201: "Created", 404: "Not Found", 500: "Internal Server Error"}
    return names.get(code, "Unknown")

18. File type

Level: Medium

A server tells the browser the file type in the Content-Type header. Write content_type(filename): for .html return text/html, for .css text/css, for .js text/javascript, for .json application/json, and for anything else application/octet-stream. Letter case in the name does not matter.

Show solution
def content_type(filename):
    types = {"html": "text/html", "css": "text/css", "js": "text/javascript", "json": "application/json"}
    extension = filename.lower().rsplit(".", 1)[-1]
    return types.get(extension, "application/octet-stream")

19. Address with parameters

Level: Medium

Write build_url(path, params): add the parameters from a dictionary to the path. "/search" and {"q": "flask", "page": 2} must give /search?q=flask&page=2. If the dictionary is empty, return the path without a question mark.

Show solution
def build_url(path, params):
    if not params:
        return path
    pairs = [f"{key}={value}" for key, value in params.items()]
    return path + "?" + "&".join(pairs)

20. Parsing a cookie

Level: Medium

Write parse_cookie(header): turn the header string theme=dark; lang=kk into the dictionary {"theme": "dark", "lang": "kk"}. For an empty string return an empty dictionary. A value may contain the = sign.

Show solution
def parse_cookie(header):
    result = {}
    for part in header.split(";"):
        if "=" in part:
            key, value = part.strip().split("=", 1)
            result[key] = value
    return result

21. Safe redirect

Level: Medium

After login a site sends the person back to the address from the next parameter. Write is_safe_redirect(url): return True only if the address leads to the same site, that is, starts with a single slash /. The browser treats //evil.example as another site.

Show solution
def is_safe_redirect(url):
    return url.startswith("/") and not url.startswith("//")

Forms and data checks

The server checks everything a user sends on its own.

22. Clean title

Level: Easy

Write clean_title(value): remove the spaces at both ends and replace several spaces in a row inside with one. " Buy bread " must become Buy bread.

Show solution
def clean_title(value):
    return " ".join(value.split())

23. A number from a form

Level: Medium

Form fields always arrive as strings. Write to_int(value, default): turn the string into a whole number. Spaces at the ends are fine. If the string is not a number, return default.

Show solution
def to_int(value, default):
    try:
        return int(value.strip())
    except ValueError:
        return default

24. Required fields

Level: Medium

Write missing_fields(data, required). data is a dictionary with form data, required is a list of required fields. Return the list of fields that are missing from the dictionary or empty. A string of spaces is empty too. Keep the order of required.

Show solution
def missing_fields(data, required):
    return [name for name in required if not str(data.get(name, "")).strip()]

25. Safe output

Level: Medium

Write escape_html(text): replace & with &amp;, < with &lt; and > with &gt;. Then text from a user shows up on the page as text and does not become a tag.

Show solution
def escape_html(text):
    text = text.replace("&", "&amp;")
    text = text.replace("<", "&lt;")
    return text.replace(">", "&gt;")

26. Looks like an email

Level: Hard

Write is_email(value): a rough check of an email address. The address has no spaces, exactly one @ sign, at least one character before it, and after it a dot that is neither first nor last.

Show solution
def is_email(value):
    if " " in value or value.count("@") != 1:
        return False
    name, domain = value.split("@")
    if not name or "." not in domain:
        return False
    return not domain.startswith(".") and not domain.endswith(".")

SQL

A real SQLite database runs right in the browser.

27. Safe insert

Level: Medium

Write add_task(db, title): it adds a row to the tasks table and returns its id. Use the ? parameter: text with a quote must not break the query.

Show solution
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT)")

def add_task(db, title):
    cursor = db.execute("INSERT INTO tasks (title) VALUES (?)", (title,))
    db.commit()
    return cursor.lastrowid

28. Selecting with a condition

Level: Easy

Write active_titles(db): return the list of titles with done = 0, sorted alphabetically.

Show solution
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE tasks (title TEXT, done INTEGER)")
db.executemany("INSERT INTO tasks VALUES (?, ?)", [("B", 0), ("A", 0), ("C", 1)])

def active_titles(db):
    rows = db.execute("SELECT title FROM tasks WHERE done = 0 ORDER BY title")
    return [row[0] for row in rows]

29. How many are left

Level: Easy

Write count_active(db): return the number of tasks where done = 0. The database must do the counting, not Python.

Show solution
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, done INTEGER)")
db.executemany("INSERT INTO tasks (title, done) VALUES (?, ?)", [("Buy bread", 1), ("Learn Flask", 0), ("Write tests", 0)])

def count_active(db):
    row = db.execute("SELECT COUNT(*) FROM tasks WHERE done = 0").fetchone()
    return row[0]

30. Delete the finished

Level: Easy

Write delete_done(db): delete every finished task (done = 1) and return how many rows were deleted.

Show solution
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, done INTEGER)")
db.executemany("INSERT INTO tasks (title, done) VALUES (?, ?)", [("Buy bread", 1), ("Learn Flask", 0), ("Write tests", 0)])

def delete_done(db):
    cursor = db.execute("DELETE FROM tasks WHERE done = 1")
    db.commit()
    return cursor.rowcount

31. Mark as done

Level: Medium

Write mark_done(db, task_id): set done = 1 for the task with this number. Return True if there was such a task and False if there was not. Other tasks must stay unchanged.

Show solution
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, done INTEGER)")
db.executemany("INSERT INTO tasks (title, done) VALUES (?, ?)", [("Buy bread", 1), ("Learn Flask", 0), ("Write tests", 0)])

def mark_done(db, task_id):
    cursor = db.execute("UPDATE tasks SET done = 1 WHERE id = ?", (task_id,))
    db.commit()
    return cursor.rowcount == 1

32. Text search

Level: Hard

Write search(db, text): return the titles of tasks that contain text, ordered by id. Pass the text through a ? parameter so that a quote in the search cannot break the query.

Show solution
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, done INTEGER)")
db.executemany("INSERT INTO tasks (title, done) VALUES (?, ?)", [("Buy bread", 1), ("Learn Flask", 0), ("Write tests", 0)])

def search(db, text):
    rows = db.execute("SELECT title FROM tasks WHERE title LIKE ? ORDER BY id", ("%" + text + "%",))
    return [row[0] for row in rows]

Flask

Real Flask. The first check also downloads the package from PyPI.

33. The first route

Level: Easy

Add a route GET /hello/<name> that returns the JSON {"message": "Hello, name!"}.

Show solution
from flask import Flask

app = Flask(__name__)

@app.get("/hello/<name>")
def hello(name):
    return {"message": f"Hello, {name}!"}

34. A filter in the address

Level: Medium

Make GET /tasks that returns the JSON list of tasks from TASKS. If the address has ?done=1, return only the finished ones; with ?done=0, only the unfinished ones. Without the parameter, return them all.

Show solution
from flask import Flask, request

app = Flask(__name__)
TASKS = [
    {"title": "Buy bread", "done": True},
    {"title": "Learn Flask", "done": False},
]

@app.get("/tasks")
def tasks():
    done = request.args.get("done")
    if done is None:
        return TASKS
    return [task for task in TASKS if task["done"] == (done == "1")]

35. Creating a record

Level: Hard

Make POST /items. It reads JSON with a title field. If the field is missing or empty, return {"error": "title"} with code 400. Otherwise add the title to the items list and return {"title": ...} with code 201.

Show solution
from flask import Flask, request

app = Flask(__name__)
items = []

@app.post("/items")
def create_item():
    data = request.get_json(silent=True) or {}
    title = str(data.get("title", "")).strip()
    if not title:
        return {"error": "title"}, 400
    items.append(title)
    return {"title": title}, 201

36. One record or 404

Level: Hard

Make GET /tasks/<int:task_id>. If a task with that number is in the TASKS dictionary, return its JSON. If not, return {"error": "not found"} with code 404.

Show solution
from flask import Flask

app = Flask(__name__)
TASKS = {
    1: {"id": 1, "title": "Buy bread"},
    2: {"id": 2, "title": "Learn Flask"},
}

@app.get("/tasks/<int:task_id>")
def task_detail(task_id):
    task = TASKS.get(task_id)
    if task is None:
        return {"error": "not found"}, 404
    return task

37. Health check

Level: Easy

Add a route GET /health that returns the JSON {"status": "ok"}. Such an address is made to check that the server is alive. It must not answer POST.

Show solution
from flask import Flask

app = Flask(__name__)

@app.get("/health")
def health():
    return {"status": "ok"}

38. A number in the address

Level: Easy

Make GET /square/<int:n>: return JSON with the number and its square, for example {"n": 4, "square": 16}. The address /square/abc must give 404.

Show solution
from flask import Flask

app = Flask(__name__)

@app.get("/square/<int:n>")
def square(n):
    return {"n": n, "square": n * n}

39. Required parameter

Level: Medium

Make GET /search. If the address has a non-empty q parameter, return {"q": value}. If the parameter is missing or made of spaces, return {"error": "q"} with code 400.

Show solution
from flask import Flask, request

app = Flask(__name__)

@app.get("/search")
def search():
    q = request.args.get("q", "").strip()
    if not q:
        return {"error": "q"}, 400
    return {"q": q}

40. Delete by number

Level: Hard

Make DELETE /tasks/<int:task_id>. If the task is in the TASKS dictionary, delete it and return an empty response with code 204. If it is not there, return {"error": "not found"} with code 404.

Show solution
from flask import Flask

app = Flask(__name__)
TASKS = {1: "Buy bread", 2: "Learn Flask"}

@app.delete("/tasks/<int:task_id>")
def delete_task(task_id):
    if task_id not in TASKS:
        return {"error": "not found"}, 404
    del TASKS[task_id]
    return "", 204

Ready for more?

Build a blog API with a database and tests.