The earlier example of procedural abstraction called upon a Python function called sqrt
from the math module to compute the square root. In general, we can hide the details of any computation by defining a function. A function definition requires a name, a group of parameters, and a body. It may also explicitly return a value. For example, the simple function defined below returns the square of the value you pass into it.
>>> def square(n):... return n**2...>>> square(3)9>>> square(square(3))81>>>
The syntax for this function definition includes the name, square
, and a parenthesized list of formal parameters. For this function, n
is the only formal parameter, which suggests that square
needs only one piece of data to do its work. The details, hidden “inside the box,” simply compute the result of n**2
and return it. We can invoke or call the square
function by asking the Python environment to evaluate it, passing an actual parameter value, in this case, 3
. Note that the call to square
returns an integer that can in turn be passed to another invocation.
We could implement our own square root function by using a well-known technique called “Newton’s Method.” Newton’s Method for approximating square roots performs an iterative computation that converges on the correct value. The equation newguess=1/2∗(oldguess+n/oldguess) takes a value n and repeatedly guesses the square root by making each newguessthe oldguessin the subsequent iteration. The initial guess used here is n2. Listing 1 shows a function definition that accepts a value n and returns the square root of n after making 20 guesses. Again, the details of Newton’s Method are hidden inside the function definition and the user does not have to know anything about the implementation to use the function for its intended purpose. Listing 1 also shows the use of the # character as a comment marker. Any characters that follow the # on a line are ignored.
Listing 1
def squareroot(n): root = n/2 #initial guess will be 1/2 of n for k in range(20): root = (1/2)*(root + (n / root)) return root
>>>squareroot(9)3.0>>>squareroot(4563)67.549981495186216>>>