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
- Write
safe_divide(a, b), which returnsa / b, but catchesZeroDivisionErrorand returnsNoneinstead of crashing. Write aunittest.TestCasefor it with at least twotest_methods: one for a normal division, one for division by zero. - Write
parse_int(value), which tries to convertvalueto an integer withint(), catchingValueErrorand returningNonefor anything that doesn’t convert cleanly. Test it against"42","abc", and" 17 ". - Take one of the two functions above and replace its
print()debugging statements (add a few if it has none) withloggingcalls at appropriate levels:logging.info()for a successful conversion,logging.warning()for a failed one.
Part II: Modules and Packages
- Create a module called
text_utils.pywith two functions of your own (for example,word_count(text)andtitle_case(text)), then import and use both from a separate script. - Add an
if __name__ == "__main__":block totext_utils.pythat 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. - Turn
text_utils.pyinto 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 canfrom your_package import word_count, some_other_functionwithout knowing the internal file layout.
Part III: Useful Built-ins
- Write
random_password(length), which usesrandom.choiceto build a random string of the given length from letters and digits. - Given a paragraph of text, use
collections.Counterto find and print its three most common words.
Part IV: Command-Line Arguments
- What’s the difference between
sys.argvandargparse? - Write a script that accepts a required positional argument and an optional
--timesargument withargparse, 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.