has a wide assortment of functions and predefined variables we can use to do so.
For instance, say we want to figure out the radius of a circle with an area of 100 sq. inches. The formula to calculate this is \(radius = \sqrt{\frac{area}{\pi}}\text{.}\) The math library has a math.sqrt(number) function that will give us the square root of whatever value we give. It also has a built-in value for pi (\({\pi}\)) that can be accessed as math.pi.
To make use of these, we need to first import math to make the math library available to use in our program. We then can access things like math.sqrt and math.pi.
An important detail to notice is that math.sqrt returns an answer to us that we must do something with. Just like the line of code x * 2 doesn’t do anything unless we store the result, (something like y = x * 2), writing math.sqrt(area / math.pi) would do the math, but then throw away the answer. We need to store the answer into a variable if we want to do anything with it.
Checkpoint14.10.2.
If you delete the line that says import math from Listing 14.10.1, what happens when you run the code?
Nothing, it runs just the same
Did you try it?
The line that has math.sqrt reports an error that "name ’math’ was not defined"
Correct
The line that has math.sqrt reports an error that "library ’math’ was not included"
Try it!
The program runs and silently fails without displaying anything.
Try it!
You do not need to worry about memorizing these, we will introduce them again in later chapters as needed. But here are some more examples of math library functions.
Table14.10.3.Python math functions
Name
Input
Description
math.ceil
number
Returns the smallest integer (whole number) that is greater than or equal to the number. math.ceil(4.2) would give 5.
math.floor
number
Returns the largest integer (whole number) that is less than or equal to the number. math.floor(4.9) would give 4.