Python math Module: sqrt, pi, ceil and floor
Square Root and Pi: math.sqrt() and math.pi
The math module holds maths tools that plain Python doesn't have. Two you'll use most: math.sqrt() finds a square root, and math.pi is the number pi.
import math
print(math.sqrt(144))
print(math.sqrt(2))
print(math.pi)12.0 1.4142135623730951 3.141592653589793
Think of it like the special keys on a calculator. A cheap calculator has + and -. A school calculator adds a √ key and a π key. import math turns Python into the school calculator.
The rules
math.sqrt(x)gives back the square root ofxas a float:math.sqrt(144)is12.0, not12.math.piis a value, not a function: no brackets. It's pi to 15 decimal places.math.eis another such value, the number e (about 2.718), used in science and money maths.- Show a long float neatly with
:.2fin an f-string, as in chapter 5.
Area of a circle
The area of a circle is pi times the radius squared:
import math
radius = 5
area = math.pi * radius ** 2
print(f"Area: {area:.2f}")Area: 78.54
Avoid: brackets after pi
import math
print(math.pi())TypeError: 'float' object is not callable
"Not callable" means "you can't put () after it". math.pi is a float, like 3.14, and you can't call a number. Write math.pi.
Avoid: the square root of a negative number
import math
print(math.sqrt(-9))ValueError: expected a nonnegative input, got -9.0
No real number times itself gives -9, so sqrt() refuses. "Nonnegative" means zero or more. Check the number with if first, or catch the ValueError with try/except from chapter 17.
Common beginner doubt: "Can't I write x ** 0.5 instead?" Yes, that's also a square root! But math.sqrt(x) says what it does, so it's easier to read.
math.sqrt(x) gives a float square root; math.pi is a value, so it has no brackets.