Python Math

Master mathematical operations and functions in Python

🔢 Mathematical Operations in Python

Python has a set of built-in math functions, including a comprehensive math module, that allows you to perform mathematical tasks on numbers. From basic arithmetic to advanced mathematical functions, Python has you covered.


# Basic math operations in Python
a = 10
b = 3
print(a + b)    # Addition: 13
print(a - b)    # Subtraction: 7
print(a * b)    # Multiplication: 30
print(a // b)   # Floor division: 3
print(a % b)    # Modulus (remainder): 1
print(a ** b)   # Exponentiation: 1000
                                    
Built-in
Functions
Math
Module
Powerful
Operations

Built-in Math Functions

Python provides several built-in functions for common mathematical operations:

📊

min() & max()

Find the smallest and largest values

min(5, 10, 25) max(5, 10, 25)
🔄

abs()

Returns the absolute (positive) value

abs(-7.25)

pow()

Returns x to the power of y

pow(4, 3)
🎯

round()

Rounds a number to specified decimal places

round(3.14159, 2)
builtin_math.py
# min() and max()
x = min(5, 10, 25)
y = max(5, 10, 25)
print(f"Min: {x}, Max: {y}")

# abs()
a = abs(-7.25)
print(f"Absolute value of -7.25: {a}")

# pow(x, y)
b = pow(4, 3)  # 4*4*4
print(f"4 to the power of 3: {b}")

# round()
c = round(3.14159, 2)
d = round(7.8)
print(f"Rounded 3.14159 to 2 decimal places: {c}")
print(f"Rounded 7.8: {d}")

# Working with lists
numbers = [1, 5, 3, 9, 2, 8]
print(f"Numbers: {numbers}")
print(f"Min: {min(numbers)}")
print(f"Max: {max(numbers)}")
print(f"Sum: {sum(numbers)}")
print(f"Length: {len(numbers)}")

# Practical example: Calculate average
average = sum(numbers) / len(numbers)
print(f"Average: {round(average, 2)}")

The math Module

Python has a built-in module called math , which provides more advanced mathematical functions and constants. To use it, you must import it:

Import math module
import math

📋 Common math Module Functions:

📈

Rounding Functions

  • math.ceil(x) - Round up
  • math.floor(x) - Round down

Power & Root

  • math.sqrt(x) - Square root
  • math.pow(x, y) - x to power y
π

Constants

  • math.pi - Value of π
  • math.e - Euler's number
📐

Trigonometry

  • math.sin(x) - Sine
  • math.cos(x) - Cosine
  • math.tan(x) - Tangent
📊

Logarithms

  • math.log(x) - Natural log
  • math.log10(x) - Base 10 log
🔄

Conversions

  • math.degrees(x) - Radians to degrees
  • math.radians(x) - Degrees to radians
math_examples.py
import math

print("Math Module Examples")
print("=" * 30)

# Rounding functions
print("Rounding Functions:")
x = 1.4
print(f"math.ceil({x}) = {math.ceil(x)}")   # Round up
print(f"math.floor({x}) = {math.floor(x)}")  # Round down

# Square root
print(f"\nSquare root:")
print(f"math.sqrt(64) = {math.sqrt(64)}")
print(f"math.sqrt(2) = {math.sqrt(2):.4f}")

# Constants
print(f"\nMath Constants:")
print(f"π (pi) = {math.pi:.6f}")
print(f"e (Euler's number) = {math.e:.6f}")

# Logarithms
print(f"\nLogarithms:")
print(f"math.log10(100) = {math.log10(100)}")  # Base 10
print(f"math.log(20) = {math.log(20):.4f}")    # Natural log

# Trigonometric functions
print(f"\nTrigonometry:")
angle_degrees = 45
angle_radians = math.radians(angle_degrees)
print(f"45 degrees = {angle_radians:.4f} radians")
print(f"sin(45°) = {math.sin(angle_radians):.4f}")
print(f"cos(45°) = {math.cos(angle_radians):.4f}")
print(f"tan(45°) = {math.tan(angle_radians):.4f}")

# Power functions
print(f"\nPower Functions:")
print(f"math.pow(2, 3) = {math.pow(2, 3)}")
print(f"2 ** 3 = {2 ** 3}")  # Alternative syntax

# Factorial
print(f"\nFactorial:")
print(f"math.factorial(5) = {math.factorial(5)}")  # 5! = 5*4*3*2*1

# GCD (Greatest Common Divisor)
print(f"\nGCD:")
print(f"math.gcd(48, 18) = {math.gcd(48, 18)}")

Real-World Applications

🏠

Area Calculator

Calculate areas of different shapes

area_calculator.py
import math

def calculate_circle_area(radius):
    """Calculate area of a circle"""
    return math.pi * pow(radius, 2)

def calculate_triangle_area(base, height):
    """Calculate area of a triangle"""
    return 0.5 * base * height

def calculate_rectangle_area(length, width):
    """Calculate area of a rectangle"""
    return length * width

# Example usage:
radius = 5
base = 10
height = 7
length = 8
width = 6

print("Area Calculator")
print("=" * 20)
print(f"Circle (r={radius}): {calculate_circle_area(radius):.2f}")
print(f"Triangle (b={base}, h={height}): {calculate_triangle_area(base, height):.2f}")
print(f"Rectangle (l={length}, w={width}): {calculate_rectangle_area(length, width):.2f}")
📐

Distance Calculator

Calculate distance between two points

distance_calculator.py
import math

def calculate_distance(x1, y1, x2, y2):
    """Calculate distance between two points using Pythagorean theorem"""
    return math.sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))

# Example: Distance between (0, 0) and (3, 4)
point1 = (0, 0)
point2 = (3, 4)

distance = calculate_distance(point1[0], point1[1], point2[0], point2[1])
print(f"Distance between {point1} and {point2}: {distance:.2f}")

🏋️ Practice Exercise: Hypotenuse Calculator

Write a Python script that calculates the length of the hypotenuse (c) using the Pythagorean theorem: c = √(a² + b²)

Your Task:

  1. Import the math module
  2. Ask the user for side 'a' and side 'b'
  3. Calculate the hypotenuse using math.sqrt()
  4. Display the result formatted to 2 decimal places
  5. Handle invalid input with error checking
hypotenuse_calculator.py
import math

def calculate_hypotenuse(a, b):
    """Calculate hypotenuse using Pythagorean theorem"""
    return math.sqrt(pow(a, 2) + pow(b, 2))

def main():
    print("🔺 Hypotenuse Calculator")
    print("Using Pythagorean theorem: c = √(a² + b²)")
    print("=" * 40)
    
    try:
        # Get input from user
        side_a = float(input("Enter the length of side 'a': "))
        side_b = float(input("Enter the length of side 'b': "))
        
        # Validate input
        if side_a <= 0 or side_b <= 0:
            print("❌ Error: Side lengths must be positive numbers.")
            return
        
        # Calculate hypotenuse
        hypotenuse = calculate_hypotenuse(side_a, side_b)
        
        # Display results
        print(f"\n📊 Results:")
        print(f"Side a: {side_a}")
        print(f"Side b: {side_b}")
        print(f"Hypotenuse c: {hypotenuse:.2f}")
        
        # Additional calculations
        perimeter = side_a + side_b + hypotenuse
        area = 0.5 * side_a * side_b
        
        print(f"\n📐 Additional Info:")
        print(f"Perimeter: {perimeter:.2f}")
        print(f"Area: {area:.2f}")
        
    except ValueError:
        print("❌ Error: Please enter valid numeric values.")
    except Exception as e:
        print(f"❌ An unexpected error occurred: {e}")

if __name__ == "__main__":
    main()

Advanced Math Operations

Let's explore some advanced mathematical operations and their practical applications.

advanced_math.py
import math

# Statistical functions
def calculate_mean(numbers):
    """Calculate arithmetic mean"""
    return sum(numbers) / len(numbers)

def calculate_median(numbers):
    """Calculate median"""
    sorted_nums = sorted(numbers)
    n = len(sorted_nums)
    if n % 2 == 0:
        return (sorted_nums[n//2 - 1] + sorted_nums[n//2]) / 2
    else:
        return sorted_nums[n//2]

def calculate_standard_deviation(numbers):
    """Calculate standard deviation"""
    mean = calculate_mean(numbers)
    variance = sum((x - mean) ** 2 for x in numbers) / len(numbers)
    return math.sqrt(variance)

# Compound interest calculator
def compound_interest(principal, rate, time, n=1):
    """
    Calculate compound interest
    A = P(1 + r/n)^(nt)
    """
    amount = principal * (1 + rate/n) ** (n * time)
    interest = amount - principal
    return amount, interest

# Example usage
print("📊 Advanced Math Operations")
print("=" * 40)

# Statistical analysis
test_scores = [85, 92, 78, 96, 88, 91, 84, 89, 93, 87]
print(f"Test Scores: {test_scores}")
print(f"Mean: {calculate_mean(test_scores):.2f}")
print(f"Median: {calculate_median(test_scores):.2f}")
print(f"Standard Deviation: {calculate_standard_deviation(test_scores):.2f}")

# Compound interest calculation
principal = 1000  # Initial amount
rate = 0.05      # 5% annual interest rate
time = 5         # 5 years
n = 12           # Compounded monthly

amount, interest = compound_interest(principal, rate, time, n)
print(f"\n💰 Compound Interest Calculation:")
print(f"Principal: ${principal:,.2f}")
print(f"Rate: {rate*100}% per year")
print(f"Time: {time} years")
print(f"Compounded: {n} times per year")
print(f"Final Amount: ${amount:,.2f}")
print(f"Interest Earned: ${interest:,.2f}")

# Trigonometry in real world - calculating height of building
def calculate_building_height(distance, angle_degrees):
    """Calculate building height using trigonometry"""
    angle_radians = math.radians(angle_degrees)
    height = distance * math.tan(angle_radians)
    return height

distance_from_building = 50  # meters
angle_of_elevation = 30      # degrees

building_height = calculate_building_height(distance_from_building, angle_of_elevation)
print(f"\n🏢 Building Height Calculation:")
print(f"Distance from building: {distance_from_building} meters")
print(f"Angle of elevation: {angle_of_elevation}°")
print(f"Building height: {building_height:.2f} meters")

# Number theory - Prime number checker
def is_prime(n):
    """Check if a number is prime"""
    if n < 2:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

# Find prime numbers up to 50
primes = [n for n in range(2, 51) if is_prime(n)]
print(f"\n🔢 Prime numbers up to 50:")
print(primes)

🧠 Test Your Knowledge

Which built-in function returns the absolute value of a number?

To use math.sqrt(), what must you do first?

What does math.ceil(4.2) return?