🐍 Python for Everyone

← Back to practice bank

Chapter 31 Coding Challenges 45-60 min, auto-graded

Coding Challenges: Professional Python

8 HackerRank-style challenges, auto-graded right in your browser — no local install needed, standard library only. Most of these are real, runnable logging and argparse code, since those are genuine gradeable Python logic; a few reason about venv/pip/packaging behavior using plain data, the same way Chapter 28's git challenges worked, since those topics are mostly command-line and config-file skills rather than Python logic. Write your function in the code box, then click Run Tests to check it against a set of test cases (including edge cases). Stuck? Every challenge has a Show Solution reveal at the bottom.

How grading works Your code runs entirely in your browser using Pyodide (Python compiled to WebAssembly) — nothing is uploaded anywhere. Keep the function name in the stub exactly as given, since the grader calls it by name. The logging/argparse challenges use the real standard library modules; the venv/packaging challenges' expected values were checked against real pip/venv behavior in a scratch directory before being written into these tests.

1 Log Level Number to Name Easy

Write a function level_name_for_number(level_number) that returns the standard logging level name for a given numeric level, using Python's logging module. The standard mapping is: 10 → "DEBUG", 20 → "INFO", 30 → "WARNING", 40 → "ERROR", 50 → "CRITICAL".

Constraints: level_number is one of 10, 20, 30, 40, 50.
Examples:
level_name_for_number(30) → "WARNING"
level_name_for_number(10) → "DEBUG"
challenge_1.py
Show Solution
solution_1.py
import logging

def level_name_for_number(level_number):
    return logging.getLevelName(level_number)

2 Would This Message Be Emitted? Easy

Write a function would_message_be_emitted(logger_level, message_level). A logger only emits (handles) a message if the message's numeric level is greater than or equal to the logger's configured threshold level -- e.g. a logger set to 30 (WARNING) emits a 40 (ERROR) message but suppresses a 20 (INFO) message. Return True if the message would be emitted, else False.

Constraints: both arguments are ints among 10, 20, 30, 40, 50.
Examples:
would_message_be_emitted(30, 20) → False
would_message_be_emitted(30, 40) → True
challenge_2.py
Show Solution
solution_2.py
def would_message_be_emitted(logger_level, message_level):
    return message_level >= logger_level

3 Parse Real CLI Arguments Medium

Write a function parse_cli_args(argv) that builds an argparse.ArgumentParser with one required positional argument "filename", one optional flag "--verbose" (action="store_true"), and one optional flag "--output" that takes a value (default None). Parse the list argv with it and return a dict with keys "filename", "verbose", and "output" holding the parsed values.

Constraints: argv is a list of strings that always includes exactly one filename and zero or more of the optional flags.
Examples:
parse_cli_args(["data.csv"]) → {"filename": "data.csv", "verbose": False, "output": None}
parse_cli_args(["data.csv", "--verbose"]) → {"filename": "data.csv", "verbose": True, "output": None}
challenge_3.py
Show Solution
solution_3.py
import argparse

def parse_cli_args(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("filename")
    parser.add_argument("--verbose", action="store_true")
    parser.add_argument("--output", default=None)
    ns = parser.parse_args(argv)
    return {"filename": ns.filename, "verbose": ns.verbose, "output": ns.output}

4 A Count-Style Verbosity Flag Medium

Write a function count_verbosity(argv) that builds an argparse.ArgumentParser with one optional flag "--verbose" using action="count" and default=0, so passing the flag multiple times increases a count. Parse argv with it and return the resulting count as an int.

Constraints: argv is a list of strings containing zero or more "--verbose" entries and nothing else.
Examples:
count_verbosity([]) → 0
count_verbosity(["--verbose", "--verbose"]) → 2
challenge_4.py
Show Solution
solution_4.py
import argparse

def count_verbosity(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("--verbose", action="count", default=0)
    ns = parser.parse_args(argv)
    return ns.verbose

5 Count Emitted Messages Medium

Write a function count_emitted_messages(logger_level, message_levels). Given a logger's numeric threshold level and a list of numeric levels for messages that code attempted to log, return how many of those messages would actually be emitted (i.e. how many have a level greater than or equal to logger_level).

Constraints: logger_level is an int; message_levels is a list of ints (may be empty).
Examples:
count_emitted_messages(30, [10, 20, 30, 40, 50]) → 3
challenge_5.py
Show Solution
solution_5.py
def count_emitted_messages(logger_level, message_levels):
    return sum(1 for lvl in message_levels if lvl >= logger_level)

6 Classify a Dependency Pin Style Easy

Write a function dependency_pin_style(version_spec) that classifies a dependency version specifier string's pin style. Return "exact" if it contains "==", "compatible" if it contains "~=", "minimum" if it contains ">=" (and neither of the above), or "unpinned" if it's an empty string or matches none of these (no version constraint at all, just the bare package name).

Constraints: version_spec is a string; check in this priority order: exact, then compatible, then minimum, else unpinned.
Examples:
dependency_pin_style("==2.34.2") → "exact"
dependency_pin_style("") → "unpinned"
challenge_6.py
Show Solution
solution_6.py
def dependency_pin_style(version_spec):
    if version_spec == "":
        return "unpinned"
    if "==" in version_spec:
        return "exact"
    if "~=" in version_spec:
        return "compatible"
    if ">=" in version_spec:
        return "minimum"
    return "unpinned"

7 Parse pip freeze Output Medium

Write a function parse_pip_freeze(freeze_output) that takes the multi-line string output of pip freeze (one "package==version" per line) and returns a dict mapping each package name to its version string. Ignore blank lines.

Constraints: freeze_output is a string; each non-blank line has exactly one "==".
Examples:
parse_pip_freeze("requests==2.34.2\nidna==3.18") → {"requests": "2.34.2", "idna": "3.18"}
challenge_7.py
Show Solution
solution_7.py
def parse_pip_freeze(freeze_output):
    result = {}
    for line in freeze_output.splitlines():
        line = line.strip()
        if not line:
            continue
        name, version = line.split("==")
        result[name] = version
    return result

8 Build a CLI Entry-Point Line Easy

Write a function cli_entry_point_line(package_name, module_name, function_name) that returns the exact line format used inside a pyproject.toml's [project.scripts] table to register a CLI command: {package_name} = "{module_name}:{function_name}" (e.g. mycli = "mycli.cli:main").

Constraints: all three arguments are non-empty strings.
Examples:
cli_entry_point_line("mycli", "mycli.cli", "main") → 'mycli = "mycli.cli:main"'
challenge_8.py
Show Solution
solution_8.py
def cli_entry_point_line(package_name, module_name, function_name):
    return f'{package_name} = "{module_name}:{function_name}"'
← Practice Bank Interview Questions →