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.

  1. Finding Minimum and Maximum Values
    • Example Code:

      python
      x = min(5, 10, 25)
      y = max(5, 10, 25)
      
      print(x)  # Output: 5
      print(y)  # Output: 25
      
  2. Getting the Absolute Value
    • Example Code:

      python
      x = abs(-7.25)
      print(x)  # Output: 7.25
      
  3. Calculating Power
    • Example Code:

      python
      x = 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

  1. Calculating the Square Root
    • Example Code:

      python
      import math
      
      x = math.sqrt(64)
      print(x)  # Output: 8.0
      
  2. Rounding Numbers
    • Example Code:

      python
      import math
      
      x = math.ceil(1.4)
      y = math.floor(1.4)
      
      print(x)  # Output: 2
      print(y)  # Output: 1
      
  3. Getting the Value of Pi
    • Example Code:

      python
      import math
      
      x = math.pi
      print(x)  # Output: 3.141592653589793
      

Try It Yourself: Fun Exercises

  1. Find Your Lucky Number:
    • Use the min() and max() functions to find the smallest and largest numbers in a list of your favorite numbers.
  2. Calculate Distances:
    • Write a program to calculate the absolute difference between two numbers using the abs() function.
  3. Explore Powers:
    • Use the pow() function to calculate different powers, like 2^4 and 3^5.

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!