🐍 Python for Everyone

← Back to the quiz

Chapter 31 Exercises 40 min, hands-on

Exercises: Professional Python

How to run these Download starter.py below (it has every function signature and detailed instructions as comments) and run python3 starter.py from inside the folder you saved it in. Everything here uses only the standard library (argparse, logging) — no pip install or virtual environment required to complete the tasks themselves.

1 make_logger(name, level=logging.INFO)

Create and return a logger via logging.getLogger(name), set its level, and attach one StreamHandler with formatter "%(levelname)s: %(message)s". Only add the handler if logger.handlers is empty — otherwise calling this twice with the same name prints every message twice.

2 safe_divide(logger, a, b)

If b is 0, log an error describing the attempted division and return None. Otherwise compute a / b, log it at INFO level, and return the result.

3 build_greet_parser()

Return an argparse.ArgumentParser with prog="greet": a required positional name, an optional -g/--greeting (default "Hello"), and an optional -n/--times (type=int, default 1). Give every argument a help= string.

4 build_greeting(args)

Given a parsed Namespace from Task 3's parser, return "{greeting}, {name}!" repeated on its own line, args.times times, joined with newlines.

5 build_task_parser()

Return an argparse.ArgumentParser with prog="taskcli" and two subcommands via add_subparsers(dest="command", required=True): "add" (one required positional description) and "list" (one optional flag --all using action="store_true").

🐞 Task 6 — Debug the Code

broken_logger_setup() is supposed to print WARNING-level messages and above to the console — but it prints nothing at all, no matter what level you log at. Find the bug and fix it, without changing the intended threshold.

starter.py (broken)
def broken_logger_setup():
    logger = logging.getLogger("broken")
    logger.setLevel(logging.WARNING)
    handler = logging.StreamHandler()
    handler.setLevel(logging.CRITICAL)  # bug is somewhere in this function
    logger.addHandler(handler)
    return logger

Hint: a message has to pass two separate level checks before it prints — the logger's own level, and the handler's level. Whichever one is stricter wins.

Checking your work Run python3 solution.py and compare its output against your own. safe_divide(logger, 10, 2) should log at INFO and return 5.0; safe_divide(logger, 5, 0) should log at ERROR and return None. After fixing Task 6, fixed_logger_setup().warning(...) should actually print, while .info(...) on that same logger still shouldn't (it's below WARNING). Every function in solution.py was actually run and verified before being published, including every argparse call via an explicit args list.
← Back to Quiz Practice Bank →