Python Math
When you need to do mathematical work on numbers, Python offers a set of built-in functions, along with a large math module.
Built-in Math Functions
To find the smallest or largest value in an iterable, use min() or max():
Example
Prompt
Use
min() and max() to find the lowest and highest values among 5, 10, and 25.
Print both results.
Output: complete Python program
main.py
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
Example
Prompt
Use the
abs() function to return the absolute value of -7.25.
Print the result.
Output: complete Python program
main.py
x = abs(-7.25)
print(x)
Example
Work out 4 cubed, meaning 4 * 4 * 4:
Prompt
Use the
pow() function to return the value of 4 to the power of 3.
Print the result.
Output: complete Python program
main.py
x = pow(4, 3)
print(x)
The Math Module
Python also has a built-in module named math, which adds many more mathematical functions to the ones above.
Before you can use it, you have to import it:
Once that import is done, the module's functions and constants are ready to use.
For example, math.sqrt() calculates a number's square root and returns it:
Example
Prompt
Import the
math module and use math.sqrt() to find the square root of 64.
Print the result.
Output: complete Python program
main.py
import math
x = math.sqrt(64)
print(x)
Example
Prompt
Import the
math module. Use math.ceil() to round 1.4 upwards and math.floor() to round 1.4 downwards.
Print both results.
Output: complete Python program
main.py
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
Example
Prompt
Import the
math module and print the value of math.pi.
Output: complete Python program
main.py
import math
x = math.pi
print(x)