Skip to main content

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

Example

Prompt
Use the abs() function to return the absolute value of -7.25. Print the result.
Output: complete Python program

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

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

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

Example

Prompt
Import the math module and print the value of math.pi.
Output: complete Python program