Math Module
What You'll Learn: In this tutorial, you'll discover Python's built-in math functions and the math module, which help you perform various mathematical tasks on numbers.
Built-in Math Functions
Python comes with several built-in math functions that can handle common mathematical operations.
- Finding Minimum and Maximum Values
Example Code:
pythonx = min(5, 10, 25) y = max(5, 10, 25) print(x) # Output: 5 print(y) # Output: 25
- Getting the Absolute Value
Example Code:
pythonx = abs(-7.25) print(x) # Output: 7.25
- Calculating Power
Example Code:
pythonx = pow(4, 3) print(x) # Output: 64 (4^3)
The Math Module
Python also has a built-in module called math, which extends the list of mathematical functions. To use it, you must import the module:
Example Code:
python
import math
Using the Math Module
- Calculating the Square Root
Example Code:
pythonimport math x = math.sqrt(64) print(x) # Output: 8.0
- Rounding Numbers
Example Code:
pythonimport math x = math.ceil(1.4) y = math.floor(1.4) print(x) # Output: 2 print(y) # Output: 1
- Getting the Value of Pi
Example Code:
pythonimport math x = math.pi print(x) # Output: 3.141592653589793
Try It Yourself: Fun Exercises
- Find Your Lucky Number:
- Use the
min()andmax()functions to find the smallest and largest numbers in a list of your favorite numbers.
- Use the
- Calculate Distances:
- Write a program to calculate the absolute difference between two numbers using the
abs()function.
- Write a program to calculate the absolute difference between two numbers using the
- Explore Powers:
- Use the
pow()function to calculate different powers, like 2^4 and 3^5.
- Use the
Summary:
In this Python tutorial, we learned about built-in math functions and the math module, which help you perform various mathematical operations. These functions are useful for handling numbers in your programs. Keep experimenting and have fun with Python!