Chapter 3 – Functions, Scoping, Recursion, and Other Miscellany

To write useful, reusable code functions are essential. In this chapter we introduce the concept of functions and demonstrate how to write them in Python. The details of calling functions and returning data given. Writing comments that describe what the function does, its parameters, and return values in the form of docstrings is detailed, and the way to print these docstrings using the help function is shown. The concept of function scope is introduced and demonstrated through examples. Recursion, or functions calling themselves, is discussed and demonstrated through the calculation of the factorial. Finally, interacting with external files in Python is discussed, in particular, writing and calling functions in other files via modules and reading and writing text files.