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.
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!.
Hint 1. The easiest way to join text and a variable is an f-string: f"Hello, {name}!".
Hint 2.name.strip() removes the spaces at both ends.
Hint 3. An empty string counts as false in a condition: name or 'guest' gives “guest” when the name is empty.
Show solution
def greet(name):
name = name.strip()
return f"Hello, {name or 'guest'}!"
case('greet("Anna")', "Hello, Anna!")
case('greet(" Erlan ")', "Hello, Erlan!", "Remove the spaces around the name: .strip() will do")
case('greet("")', "Hello, guest!", "An empty name needs the answer “Hello, guest!”")
case('greet(" ")', "Hello, guest!", "A name made only of spaces also counts as empty")
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.
Hint 1. Start with an empty dictionary counts = {} and loop over the words.
Hint 2.text.lower().split() lowercases the text and splits it on any spaces and line breaks.
Hint 3.counts.get(word, 0) + 1 increases the counter even when the word is not in the dictionary yet.
Show solution
def count_words(text):
counts = {}
for word in text.lower().split():
counts[word] = counts.get(word, 0) + 1
return counts
case('count_words("")', {}, "An empty string needs an empty dictionary")
case('count_words("Yes yes no")', {"yes": 2, "no": 1}, "Convert the words to lower case")
case('count_words("a b\\nb")', {"a": 1, "b": 2}, "Split with .split() without arguments")
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.
Hint 1.len(password) gives the length of the string.
Hint 2.any(ch.isdigit() for ch in password) returns True if the password contains a digit.
Hint 3. For letters there is ch.isalpha(). Join the three conditions with and.
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
case('is_strong("qwerty12")', True)
case('is_strong("qwe12")', False, "At least 8 characters are needed")
case('is_strong("12345678")', False, "A password without letters is not strong")
case('is_strong("password")', False, "A password without digits is not strong")
case('is_strong("pässwort2026")', True, "Letters like ä are letters too: .isalpha()")
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.
Hint 1. Go through the characters of title.lower(): a letter or digit (ch.isalnum()) stays, anything else becomes "-".
Hint 2."-".join(...) over the non-empty pieces after split("-") joins them without extra hyphens.
Hint 3. With the re module: re.sub(r"[^a-z0-9]+", "-", text).strip("-").
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)
case('slugify("Hello World")', "hello-world")
case('slugify(" Flask & Django: 2 frameworks! ")', "flask-django-2-frameworks", "Several signs in a row give one hyphen")
case('slugify("---")', "", "Hyphens at the ends must be removed")
case('slugify("Python3")', "python3", "Digits stay")
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.
Hint 1. Create a variable result = 0 and add every price to it in a for loop.
Hint 2. A shortcut: the built-in sum(prices) does the same.
Show solution
def total(prices):
result = 0
for price in prices:
result += price
return result
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 ....
Hint 1. A slice gives the first characters of a string: text[:limit].
Hint 2. Check the length first: if len(text) <= limit.
Show solution
def truncate(text, limit):
if len(text) <= limit:
return text
return text[:limit] + "..."
case('truncate("Python", 10)', "Python")
case('truncate("Python for the web", 6)', "Python...")
case('truncate("Flask", 5)', "Flask")
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.
Hint 1. Keep the best word in a variable best = "" and compare lengths with len().
Hint 2. To keep the first word when lengths are equal, compare strictly: len(word) > len(best).
Show solution
def longest(words):
best = ""
for word in words:
if len(word) > len(best):
best = word
return best
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.
Hint 1.full_name.split() splits the string into words and drops extra spaces itself.
Hint 2. The first letter of a word is part[0], and .upper() makes it capital. Join the parts with " ".join(...).
Show solution
def initials(full_name):
parts = full_name.split()
return " ".join(part[0].upper() + "." for part in parts)
case('initials("Aru Bekova")', "A. B.")
case('initials(" dana ali ")', "D. A.")
case('initials("Python")', "P.")
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 =.
Hint 1. First split the string into pairs: query.split("&").
Hint 2. Skip a pair without = with the check if "=" in part.
Hint 3.part.split("=", 1) splits only on the first =, the rest stay in the value.
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
case('parse_query("")', {}, "An empty string needs an empty dictionary")
case('parse_query("a=1&b=2")', {"a": "1", "b": "2"})
case('parse_query("flag&x=1")', {"x": "1"}, "A part without = must be skipped")
case('parse_query("token=a=b")', {"token": "a=b"}, "Split only on the first =: split('=', 1)")
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").
Hint 1. Check in order: first whether the address exists, then whether the method does.
Hint 2.path not in ROUTES means there is no such address: that is 404.
Hint 3. The address's methods are in ROUTES[path]. If the method is not there, it is 405; otherwise return 200 and the text.
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]
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.
Hint 1. The field may be missing: data.get("name", "") returns an empty string instead of an error.
Hint 2.isinstance(age, int) checks for a whole number, 1 <= age <= 120 checks the range.
Hint 3. In Python True also counts as an int. Filter it out separately: isinstance(age, bool).
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
case('validate_user({"name": "Aruzhan", "age": 20})', [], "Correct data must not give errors")
case('validate_user({"age": 20})', ["name"], "Without a name there must be a name error")
case('validate_user({"name": " ", "age": 20})', ["name"], "A name made of spaces counts as empty")
case('validate_user({"name": "A", "age": 0})', ["age"], "Age 0 is not allowed")
case('validate_user({"name": "A", "age": "20"})', ["age"], "A string does not count as a number")
case('validate_user({"name": "A", "age": True})', ["age"], "In Python True is an int too: check for it separately")
case('validate_user({})', ["name", "age"], "Return both errors in order")
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.
Hint 1. Pick the unfinished tasks: [task for task in tasks if not task["done"]].
Hint 2.json.dumps(...) turns the list into a JSON string.
Hint 3. Add ensure_ascii=False so letters like é do not become codes such as \u00e9.
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)
data = [{"title": "Café", "done": False}, {"title": "Sleep", "done": True}]
case('type(tasks_json(data)).__name__', "str", "Return a string, not a list")
case('json.loads(tasks_json(data))', [{"title": "Café", "done": False}], "Only unfinished tasks must remain in the answer")
case('"Café" in tasks_json(data)', True, "Add ensure_ascii=False, otherwise é turns into a code")
case('tasks_json([])', "[]", "An empty list needs the string []")
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.
Hint 1. The regular expression r"\{\{\s*(\w+)\s*\}\}" finds all the gaps.
Hint 2.re.sub(pattern, function, text) calls the function for every gap it finds and puts in its answer.
Hint 3. Inside the function the gap's name is match.group(1), and str(data.get(name, "")) gets the value.
case('render("Hello, {{ name }}!", {"name": "Dana"})', "Hello, Dana!")
case('render("{{a}}+{{ b }}={{c}}", {"a": 1, "b": 2, "c": 3})', "1+2=3", "Spaces inside the braces are optional, turn numbers into strings")
case('render("[{{ missing }}]", {})', "[]", "An unknown key is replaced with an empty string")
case('render("no gaps", {"x": 1})', "no gaps")
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.
Hint 1. The first item of the page is at position (page - 1) * per_page.
Hint 2. The slice items[start:start + per_page] shortens itself if there are fewer items.
Hint 3. Check a page number below 1 separately, otherwise a negative slice returns extra items.
letters = list("abcdefg")
case('paginate(letters, 1, 3)', ["a", "b", "c"])
case('paginate(letters, 3, 3)', ["g"], "The last page may have fewer items")
case('paginate(letters, 4, 3)', [], "There is no such page: an empty list is needed")
case('paginate(letters, 0, 3)', [], "There is no page number 0")
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.
Hint 1. It is handy to keep the pairs in a dictionary: {200: "OK", 404: "Not Found"}.
Hint 2.names.get(code, "Unknown") returns a fallback when the code is not in the dictionary.
A server tells the browser the file type in the Content-Type header. Write content_type(filename): for .html return text/html, for .csstext/css, for .jstext/javascript, for .jsonapplication/json, and for anything else application/octet-stream. Letter case in the name does not matter.
Hint 1. The extension is the part after the last dot: filename.rsplit(".", 1)[-1].
Hint 2. Lowercase the name with .lower() and take the type from a dictionary with .get() and a fallback.
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.
Hint 1.params.items() gives key and value pairs. Turn each one into a string f"{key}={value}".
Hint 2. Join the pairs with "&".join(pairs) and add them to the path after ?.
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)
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.
Hint 1. First split the string on ;, then strip the spaces from each part with .strip().
Hint 2.part.split("=", 1) splits only on the first equals sign, so the value a=b stays whole.
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
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.
Hint 1.url.startswith("/") checks the start of a string.
Hint 2. Add a second condition with and not: the address must not start with //.
Show solution
def is_safe_redirect(url):
return url.startswith("/") and not url.startswith("//")
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.
Hint 1.int("abc") raises ValueError. A try / except ValueError block catches it.
Hint 2. In the except block simply return the fallback: return default.
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.
Hint 1.data.get(name, "") returns an empty string when the field is missing.
Hint 2.not value.strip() checks for emptiness: nothing is left of a string of spaces after .strip().
Show solution
def missing_fields(data, required):
return [name for name in required if not str(data.get(name, "")).strip()]
Write escape_html(text): replace & with &, < with < and > with >. Then text from a user shows up on the page as text and does not become a tag.
Hint 1.text.replace("<", "<") does a replacement. Save the result: strings do not change in place.
Hint 2. Start with &. Otherwise it gets replaced a second time inside the finished <.
Show solution
def escape_html(text):
text = text.replace("&", "&")
text = text.replace("<", "<")
return text.replace(">", ">")
case('escape_html("<b>hi</b>")', "<b>hi</b>")
case('escape_html("Tom & Jerry")', "Tom & Jerry")
case('escape_html("a < b")', "a < b")
case('escape_html("<")', "&lt;")
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.
Hint 1.value.count("@") counts how many times a character appears.
Hint 2. Split the address into two parts: name, domain = value.split("@"), and check each one separately.
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(".")
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.
Hint 1. The insert query: INSERT INTO tasks (title) VALUES (?).
Hint 2. The values are passed as the second argument, a tuple: db.execute(query, (title,)). The comma after title is required.
Hint 3.execute returns a cursor, and the new row's number is in cursor.lastrowid. Do not forget db.commit().
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
case('add_task(db, "First")', 1, "Return cursor.lastrowid")
case('add_task(db, "Second")', 2, "Every new row gets the next id")
evil = "x'); DROP TABLE tasks; --"
case('add_task(db, evil)', 3, "Text with a quote must not break the query: use ?")
case('db.execute("SELECT title FROM tasks WHERE id = 3").fetchone()', (evil,), "Text with a quote must be saved as it is")
28. Selecting with a condition
Level: Easy
Write active_titles(db): return the list of titles with done = 0, sorted alphabetically.
Hint 1. You need the query SELECT title FROM tasks with the condition WHERE done = 0.
Hint 2.ORDER BY title at the end of the query sorts alphabetically.
Hint 3. Each result row is a tuple with the title first: [row[0] for row in rows].
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]
case('active_titles(db)', ["A", "B"], "Add WHERE and ORDER BY and return a list of strings")
db.execute("UPDATE tasks SET done = 1")
case('active_titles(db)', [], "If no rows match, return an empty list")
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.
Hint 1. The query SELECT COUNT(*) FROM tasks WHERE done = 0 counts rows.
Hint 2..fetchone() returns one row as a tuple, and the number is first in it: row[0].
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]
case('count_active(db)', 2)
db.execute("UPDATE tasks SET done = 1")
case('count_active(db)', 0)
30. Delete the finished
Level: Easy
Write delete_done(db): delete every finished task (done = 1) and return how many rows were deleted.
Hint 1. The delete query: DELETE FROM tasks WHERE done = 1.
Hint 2. The number of deleted rows is in cursor.rowcount. Do not forget db.commit().
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
case('delete_done(db)', 1)
case('db.execute("SELECT COUNT(*) FROM tasks").fetchone()', (2,))
case('delete_done(db)', 0)
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.
Hint 1. The update query: UPDATE tasks SET done = 1 WHERE id = ?. Without WHERE every row changes.
Hint 2.cursor.rowcount shows how many rows changed.
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
case('mark_done(db, 2)', True)
case('db.execute("SELECT done FROM tasks WHERE id = 2").fetchone()', (1,))
case('db.execute("SELECT done FROM tasks WHERE id = 3").fetchone()', (0,))
case('mark_done(db, 99)', False)
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.
Hint 1.WHERE title LIKE ? searches by part of a string, and % means “any characters”.
Hint 2. Add the percent signs to the value, not to the query: ("%" + text + "%",).
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]
client = app.test_client()
case('client.get("/hello/Python").status_code', 200, "The address /hello/Python must open with code 200")
case('client.get("/hello/Python").json', {"message": "Hello, Python!"})
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.
Hint 1.request.args.get("done") reads the parameter from the address. If it is missing, you get None.
Hint 2. The parameter arrives as a string: compare it with "1", not with a number.
Hint 3. If you return a list of dictionaries from the function, Flask turns it into JSON itself.
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")]
client = app.test_client()
case('len(client.get("/tasks").json)', 2, "Without the parameter all tasks are needed")
case('client.get("/tasks?done=1").json', [{"title": "Buy bread", "done": True}], "?done=1 — only finished ones")
case('client.get("/tasks?done=0").json', [{"title": "Learn Flask", "done": False}], "?done=0 — only unfinished ones: the parameter arrives as a string")
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.
Hint 1. A route for sending data is declared with @app.post("/items").
Hint 2.request.get_json(silent=True) or {} does not crash on something that is not JSON, it gives an empty dictionary.
Hint 3. The response code goes second: return {"error": "title"}, 400.
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
client = app.test_client()
case('client.post("/items", json={}).status_code', 400, "Without a title code 400 is needed")
case('client.post("/items", json={"title": " "}).status_code', 400, "An empty title also gives 400")
case('client.post("/items", data="not json").status_code', 400, "Invalid JSON must not cause a crash: get_json(silent=True)")
case('client.post("/items", json={"title": "Book"}).status_code', 201, "On success code 201 is needed: return {...}, 201")
case('items', ["Book"], "The title must go into the items list")
case('client.post("/items", json={"title": "Pen"}).json', {"title": "Pen"})
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.
Hint 1.<int:task_id> in the address turns part of the path into a number and passes it to the function.
Hint 2.TASKS.get(task_id) returns None if there is no such task.
Hint 3. For a missing task: return {"error": "not found"}, 404.
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.
Hint 1.request.args.get("q", "") reads the parameter: the second value comes back when it is missing.
Hint 2. The response code goes second: return {"error": "q"}, 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}
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.
Hint 1. A delete route is declared with @app.delete(...). del TASKS[task_id] removes an item from a dictionary.
Hint 2. An empty response with a code: return "", 204.
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