Choose Mathematical Functions
Core idea
The math module offers real-number operations and constants. floor(x) rounds toward negative infinity, ceil(x) toward positive infinity; sqrt(x) returns a real square root for nonnegative x. Trigonometric functions accept radians, not degrees.
import mathprint(math.floor(-2.3), math.ceil(-2.3))Floor and ceiling bound the measurement on opposite sides.
Measure a diagonal
import mathprint(math.hypot(3, 4))print(round(math.sin(math.radians(30)), 3))print(round(2 * math.pi * 3, 2))hypot computes the length of a vector; radians converts degrees before sine. pi is the circle constant; 2 * pi * radius gives circumference.
Compute an integer square root
isqrt returns the greatest integer whose square is no larger than the input.
Common mistake
int(x) truncates toward zero, not always down. sqrt of a negative real raises ValueError; complex roots belong to cmath.
Practice
Find the side length of the largest square grid that can be built from a total number of tiles: use isqrt. Try 0, 15 and 16.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Math function selection
Check your understanding of math functions.
What is printed?
import mathprint(math.floor(-4.2), math.ceil(-4.2))What is printed?
import mathprint(math.isqrt(99))Which exception occurs?
import mathmath.sqrt(-4)What should you pass to math.sin for a 90 degree angle?