JESKO GARAGE All topicsViva questions ▶ Open the practice garage

Python CLEAN CODE, DEBUGGING, JSON & WEB APIs (requests): 15 practice problems

UNIT 2 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.

▶ Practise CLEAN CODE, DEBUGGING, JSON & WEB APIs (requests) nowAll topics

Theory: CLEAN CODE, DEBUGGING, JSON & WEB APIs (requests) in Python

THEORY — CLEAN CODE (PEP 8, Python's style guide)
-------------------------------------------------
* Naming:  variables/functions  snake_case      classes  PascalCase      constants  UPPER_CASE
           "private" helpers  _leading_underscore       never: l, O, I as names; no keywords
  Identifier rules: letters/digits/_ , not starting with a digit, case-sensitive, not a keyword.
* Readability: meaningful names (total_price, not tp), 4-space indents, lines <= 79 chars,
  one statement per line, spaces around operators, blank lines between functions,
  docstrings, comments explain WHY (code shows what), avoid magic numbers (TAX_RATE = 0.18),
  DRY (Don't Repeat Yourself) -> write a function, small functions doing ONE thing.
  Tools: black (auto-format), ruff/flake8 (lint), mypy (types).

THEORY — DEBUGGING
------------------
1. Read the TRACEBACK from the BOTTOM: last line = error type + message, the line above = where.
2. Reproduce with the smallest input.   3. print() / f"{var=}" to inspect values.
4. assert condition, "message" to check assumptions.
5. VS Code debugger: F9 breakpoint · F5 start · F10 step over · F11 step into · watch variables.
   Or put breakpoint() in code (pdb: n next, s step, p var, c continue, q quit).
Common bug types: off-by-one (range(1, n) misses n), =+ instead of +=, modifying a list while
looping over it, integer division //, mutable default argument, wrong indentation, shadowing
built-ins (list = [...]), forgetting to return, comparing floats with ==.

THEORY — JSON & APIs
--------------------
* API (Application Programming Interface): a defined way for programs to talk. A WEB API is a URL
  you send HTTP requests to and get data back (usually JSON).
* HTTP methods: GET (read), POST (create/send), PUT/PATCH (update), DELETE.
  Status codes: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized,
  403 Forbidden, 404 Not Found, 429 Too Many Requests, 500 Internal Server Error.
  2xx success · 3xx redirect · 4xx client's fault · 5xx server's fault.
* JSON <-> Python:  object -> dict, array -> list, string -> str, number -> int/float,
  true/false -> True/False, null -> None.
      json.loads(text) -> Python      json.dumps(obj, indent=2, sort_keys=True) -> text
      json.load(f) / json.dump(obj, f) for files
* requests (pip install requests):
      r = requests.get(url, params={"q": "python"}, headers={...}, timeout=5)
      r.status_code   r.ok   r.raise_for_status()   r.json()   r.text
      requests.post(url, json={"name": "x"})
  ALWAYS set a timeout, and catch requests.exceptions.RequestException.
* Query strings: ?key=value&key2=value2 — build them with urllib.parse.urlencode(dict).

15 CLEAN CODE, DEBUGGING, JSON & WEB APIs (requests) practice problems

1. Mini Linter: Which Naming Style? — str methods + keyword module

Easy1 way to solve
📤 OUTPUT: return a str (text), e.g. 'snake_case'. Use `return`, not print().
Return "invalid" (not a valid identifier, or a keyword), "UPPER_CASE", "snake_case",
"PascalCase", or "other" (check in that order).
    name_style("total_price") -> "snake_case"   name_style("MAX_SIZE") -> "UPPER_CASE"
    name_style("StudentRecord") -> "PascalCase"  name_style("2fast") -> "invalid"
    name_style("class") -> "invalid"             name_style("camelCase") -> "other"
snake_case = all lowercase letters/digits/underscores. PascalCase = starts uppercase, has lowercase,
no underscores. UPPER_CASE = has uppercase letters and no lowercase letters.
Solve “Mini Linter: Which Naming Style? — str methods + keyword module” in your browser →

2. Rename to PEP 8 — camelCase / PascalCase -> snake_case

Medium2 ways to solve
📤 OUTPUT: return a str (text), e.g. 'calculate_total_price'. Use `return`, not print().
    to_snake_case("calculateTotalPrice") -> "calculate_total_price"
    to_snake_case("HTTPServer") -> "h_t_t_p_server"   (simple rule: "_" before EVERY uppercase except first char)
Solve “Rename to PEP 8 — camelCase / PascalCase -> snake_case” in your browser →

3. 🐞 Fix: should return the average, or 0.0 for an empty list.

Easy1 way to solve
📤 OUTPUT: return a float, e.g. 2.0. Use `return`, not print().
Solve “🐞 Fix: should return the average, or 0.0 for an empty list.” in your browser →

4. 🐞 Fix: should count vowels a e i o u in ANY case.

Easy1 way to solve
📤 OUTPUT: return an int, e.g. 10. Use `return`, not print().
Solve “🐞 Fix: should count vowels a e i o u in ANY case.” in your browser →

5. 🐞 Fix: should return the largest number (lists may be all negative). Empty -> None.

Easy1 way to solve
📤 OUTPUT: return an int (or None in the special case), e.g. 9. Use `return`, not print().
Solve “🐞 Fix: should return the largest number (lists may be all negative). Empty -> None.” in your browser →

6. 🐞 Fix: should return a list with all even numbers removed.

Medium1 way to solve
📤 OUTPUT: return a list, e.g. [7]. Use `return`, not print().
Solve “🐞 Fix: should return a list with all even numbers removed.” in your browser →

7. 🐞 Fix: should return 1 + 2 + ... + n (inclusive).

Easy1 way to solve
📤 OUTPUT: return an int, e.g. 55. Use `return`, not print().
Solve “🐞 Fix: should return 1 + 2 + ... + n (inclusive).” in your browser →

8. Weather App — parse a real-style API response

Medium1 way to solve
📤 OUTPUT: return a tuple, e.g. ('Pune', 27.0, 'light rain'). Use `return`, not print().
Real world: OpenWeatherMap returns JSON like:
  {"name": "Pune", "main": {"temp": 300.15, "humidity": 60},
   "weather": [{"description": "light rain"}]}
Temperature is in KELVIN. Return (city, temp_celsius rounded to 1, description).
    -> ("Pune", 27.0, "light rain")
Solve “Weather App — parse a real-style API response” in your browser →

9. Build a JSON API Response — json.dumps

Easy1 way to solve
📤 OUTPUT: return a str (text), e.g. '{"average": 60.0, "name": "Asha", "passed": t…. Use `return`, not print().
Return a JSON STRING with keys average (rounded to 1), name, passed (average >= 40),
using sort_keys=True and default separators.
    result_json("Asha", [50, 70]) -> '{"average": 60.0, "name": "Asha", "passed": true}'
Solve “Build a JSON API Response — json.dumps” in your browser →

10. Search URL With Query String — urllib.parse.urlencode

Easy2 ways to solve
📤 OUTPUT: return a str (text), e.g. 'https://api.example.com/search?q=python+ai&pa…. Use `return`, not print().
    build_url("https://api.example.com/search", {"q": "python ai", "page": 2})
    -> "https://api.example.com/search?q=python+ai&page=2"
Empty params -> base unchanged.
Solve “Search URL With Query String — urllib.parse.urlencode” in your browser →

11. Explain an HTTP Status Code

Easy2 ways to solve
📤 OUTPUT: return a str (text), e.g. 'success'. Use `return`, not print().
Return "success" (200-299), "redirect" (300-399), "client error" (400-499),
"server error" (500-599), else "unknown".
    status_category(404) -> "client error"
Solve “Explain an HTTP Status Code” in your browser →

12. Analyse API Users — json.loads + nested dicts + counting

Medium2 ways to solve
📤 OUTPUT: return a dict, e.g. {'Pune': 2, 'Delhi': 1}. Use `return`, not print().
users_json is a JSON array like jsonplaceholder.typicode.com/users:
  [{"name": "A", "address": {"city": "Pune"}}, ...]
Return {city: number_of_users}.
Solve “Analyse API Users — json.loads + nested dicts + counting” in your browser →

13. Live Data with requests — error handling + JSON

Medium1 way to solve
📤 OUTPUT: return a list of title strings ([] on any error). Use `return`, not print().
Real world: Show a user's completed tasks from a web API.
GET url (returns a JSON list of todos with "title" and "completed"), return the titles of the
completed ones. On ANY network error or bad JSON return [].
Try: https://jsonplaceholder.typicode.com/todos?userId=1
Solve “Live Data with requests — error handling + JSON” in your browser →

14. Open-Source Dependency Health Check — interview at a dev-tools company

Project1 way to solve
📤 OUTPUT: return a dict, e.g. {'repo': 'psf/requests', 'score': 90, 'grade':…. Use `return`, not print().
Interviewer: "Before we add a library, score its GitHub repo. Here's the API JSON."
today: "YYYY-MM-DD".  Start at 100 and collect issues in this order:
  archived -> -40 "archived";  license is null -> -20 "no license";
  open_issues_count >= 100 -> -15 "many open issues";
  days since pushed_at > 365 -> -25 "stale",  else > 90 -> -10 "inactive"
  stargazers_count >= 1000 -> +5.   Clamp the score to 0..100.
grade: A >= 85, B >= 70, C >= 50, else D.
Return {"repo": full_name, "score": int, "grade": str, "issues": [...]}.  Write it CLEANLY (small helpers, good names).
Solve “Open-Source Dependency Health Check — interview at a dev-tools company” in your browser →

15. Stage 14 — Diagnostics as JSON (exactly how compilers talk to VS Code: the Language Server Protocol)

Compiler1 way to solve
📤 OUTPUT: return json.dumps(..., sort_keys=True) of. Use `return`, not print().
errors: list of (line, col, message, severity).
Return json.dumps(..., sort_keys=True) of
    {"count": total, "errors": how many have severity "error",
     "diagnostics": [{"line", "col", "message", "severity"} ... sorted by line, then col]}
Solve “Stage 14 — Diagnostics as JSON (exactly how compilers talk to VS Code: the Language Server Protocol)” in your browser →

← FILE HANDLING (text & CSV) and ERROR HANDLING NUMPY (with PREREQUISITES: vectors, matrices, basic statistics) →