CodingNic

Debugging, Testing, and Modules

Debugging and Modules Exercises

Debugging, Testing, and Modules 35 min read

Debugging and Modules Exercises

Objectives

This chapter introduces no new concepts. It’s a chance to put debugging, testing, command-line arguments, and modules into practice with real code, not just recall questions.

Part I: Errors, Testing, and Logging

  1. Write safe_divide(a, b), which returns a / b, but catches ZeroDivisionError and returns None instead of crashing. Write a unittest.TestCase for it with at least two test_ methods: one for a normal division, one for division by zero.
  2. Write parse_int(value), which tries to convert value to an integer with int(), catching ValueError and returning None for anything that doesn’t convert cleanly. Test it against "42", "abc", and " 17 ".
  3. Take one of the two functions above and replace its print() debugging statements (add a few if it has none) with logging calls at appropriate levels: logging.info() for a successful conversion, logging.warning() for a failed one.

Part II: Modules and Packages

  1. Create a module called text_utils.py with two functions of your own (for example, word_count(text) and title_case(text)), then import and use both from a separate script.
  2. Add an if __name__ == "__main__": block to text_utils.py that runs a small demonstration of its own functions, and confirm it only runs when the file is executed directly, not when it’s imported elsewhere.
  3. Turn text_utils.py into a package: create a folder containing it alongside a second related module, add an __init__.py, and re-export at least one function from each so a caller can from your_package import word_count, some_other_function without knowing the internal file layout.

Part III: Useful Built-ins

  1. Write random_password(length), which uses random.choice to build a random string of the given length from letters and digits.
  2. Given a paragraph of text, use collections.Counter to find and print its three most common words.

Part IV: Command-Line Arguments

  1. What’s the difference between sys.argv and argparse?
  2. Write a script that accepts a required positional argument and an optional --times argument with argparse, and use it to repeat a message.

Recap

You can now recognize and catch common Python errors, run cleanup code with finally, log messages properly instead of relying on scattered print() calls, set breakpoints to inspect your code, write and import your own modules and packages, use useful built-ins like random, math, and collections, write automated tests with assert and unittest, and accept input from the command line with sys.argv and argparse. That’s the toolkit this module set out to build.

Next module: object-oriented programming, writing your own classes.