2. Functions and Modules
In this chapter, we consider a concept that has as profound an impact on control flow as do conditionals and loops: the function, which allows us to transfer control back and forth between different pieces of code. Functions are important because they allow us to clearly separate tasks within a program and because they provide a general mechanism that enables us to reuse code.
2.1 Defining Functions describes how to create your own functions in Python.
2.2 Modules and Clients describes how to group related functions into modules to enable modular programming.
2.3 Recursion considers the idea of a function calling itself. This possiblility is known as recursion.
2.4 Case Study: Percolation presents a case study that uses Monte Carlo simulation to study a natural model known as percolation.
Python Programs in this Chapter
Below is a list of Python programs and data files used in this chapter.
REF PROGRAM DESCRIPTION DATA 2.1.1 harmonicf.py harmonic numbers (revisited) – 2.1.2 gauss.py Gaussian functions – 2.1.3 coupon.py coupon collector (revisited) – 2.1.4 playthattunedeluxe.py play that tune (revisited) elise.txt ascale.txt stairwaytoheaven.txt entertainer.txt firstcut.txt freebird.txt looney.txt 2.2.1 gaussian.py Gaussian functions module – 2.2.2 gaussiantable.py sample Gaussian client – 2.2.3 sierpinski.py Sierpinski triangle – 2.2.4 ifs.py iterated function systems sierpinski.txt barnsley.txt coral.txt culcita.txt cyclosorus.txt dragon.txt fishbone.txt floor.txt koch.txt spiral.txt swirl.txt tree.txt zigzag.txt 2.2.5 bernoulli.py Bernoulli trials – 2.3.1 euclid.py Euclid's algorithm – 2.3.2 towersofhanoi.py towers of Hanoi – 2.3.3 beckett.py Gray code – 2.3.4 htree.py recursive graphics – 2.3.5 brownian.py Brownian bridge – 2.4.1 percolationv.py vertical percolation detection test5.txt test8.txt 2.4.2 percolationio.py percolation support functions – 2.4.3 visualizev.py vertical percolation visualization client – 2.4.4 estimatev.py vertical percolation probability estimate – 2.4.5 percolation.py percolation detection test5.txt test8.txt 2.4.6 visualize.py percolation visualization client – 2.4.7 estimate.py percolation probability estimate –