Libraries, APIs and Documentation
Two library calls
import math
side = math.sqrt(1225)
print(max(side, 40))
This prints 40. The second line calls math.sqrt and gets back 35.0. The third calls max, which returns the largest of its arguments, 40. We called two procedures and wrote neither. Both come with Python, and both were tested long before this program ran.
Importing a module
The line import math makes the name math, and math.sqrt reaches the procedure sqrt inside it. Without that line the name math doesn't exist, and the call to math.sqrt stops the program with a NameError. So the import goes at the top of the file, before any call uses it.A second form makes the name of one procedure and nothing else.
from math import floor
print(floor(7.8))
This prints 7, and the call is written floor(7.8), with no math in front.
Internal and external sources
A program can reuse code from two kinds of source. An internal source is code already in the same program, such as a function defined higher up in the file. An external source is code from outside it: the modules that ship with Python, and the ones other programmers publish.For example, a program defines to_miles at the top and calls it lower down. That call reaches an internal source. Its call to round reaches an external one, since round ships with Python.
Libraries and complex programs
math.sqrt gives a square root in one call. Writing our own root-finder means a run of repeated guesses, a rule for when to stop, and a test for negative inputs. Thus a library makes a complex program simpler to build. Someone else has written the hard part, and thousands of programs ran it before ours did.The API
Note that a call can be spelled right, run with no error, and still be wrong. What decides whether a call is right is the API.| Procedure | Takes | Gives back | The part we cannot guess |
|---|---|---|---|
math.floor(x) | one number | the largest whole number at or below x | math.floor(-3.2) is -4, not -3 |
round(x) | one number | the nearest whole number | a tie goes to the even neighbor: round(0.5) is 0 and round(1.5) is 2 |
math.pow(x, y) | two numbers | x to the power y, always a float | math.pow(2, 3) is 8.0, while 2 ** 3 is 8 |
math.sqrt(x) | one number, 0 or more | the square root, as a float | math.sqrt(-4) stops the program with a ValueError |
The last row explains the opening program. math.sqrt(1225) gave the float 35.0 rather than the int 35. Then max returned 40, the larger of the two values it was handed.
Note that no amount of care about spelling reveals the last column. A program that expects round(2.5) to be 3 runs, prints 2, and never complains. Such a program is correct by spelling and wrong by API.