Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Math Module

Python Math Module - Complete Guide

Perform mathematical calculations easily with Python's built-in math module.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • What is Math Module?
  • Math Constants
  • Basic Mathematical Functions
  • Trigonometric Functions
  • Logarithmic and Exponential Functions
  • Advanced Functions
  • Real-World Example
  • Best Practices
  • Try It Yourself
  • Quick Quiz
  • Frequently Asked Questions
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • What is math module — mathematical functions and constants
  • Constants — pi, e, tau, and infinity
  • Basic functions — sqrt, ceil, floor, pow, factorial
  • Trigonometry — sin, cos, tan, and their inverses
  • Log/Exp — log, log10, exp, expm1
  • Advanced — gcd, lcm, degrees, radians

What is Math Module?

The math module is Python's built-in library for mathematical operations. It provides a wide range of functions for basic arithmetic, trigonometry, logarithms, and more.

Think of the math module like a scientific calculator built right into Python. It has all the functions you'd expect from a calculator — square roots, trigonometry, logarithms, and constants like pi and e.

The math module is part of the standard library, so you don't need to install anything. Just import it and start calculating!

💡 Key concept: The math module gives you a comprehensive set of mathematical functions for scientific and engineering calculations.

Math Constants

1

Mathematical Constants

The math module provides several useful mathematical constants.

# Math Constants

import math

print("=" * 50)
print("MATH CONSTANTS")
print("=" * 50)

# ============================================================
# PI AND TAU
# ============================================================

print("\n1. PI AND TAU")

# π (pi) - 3.141592653589793
print(f"   math.pi = {math.pi:.10f}")

# τ (tau) - 2π = 6.283185307179586
print(f"   math.tau = {math.tau:.10f}")

# Pi is used for circles: circumference = 2 * pi * radius
radius = 5
circumference = 2 * math.pi * radius
print(f"   Circumference of circle with radius {radius}: {circumference:.2f}")


# ============================================================
# EULER'S NUMBER
# ============================================================

print("\n2. EULER'S NUMBER (e)")

# e - 2.718281828459045
print(f"   math.e = {math.e:.10f}")

# e is the base of natural logarithms
print(f"   math.exp(1) = {math.exp(1):.10f}")  # e^1 = e
print(f"   math.log(math.e) = {math.log(math.e)}")  # ln(e) = 1


# ============================================================
# INFINITY AND NAN
# ============================================================

print("\n3. INFINITY AND NAN")

# Positive infinity
print(f"   math.inf = {math.inf}")

# Negative infinity
print(f"   -math.inf = {-math.inf}")

# Not a Number (invalid result)
print(f"   math.nan = {math.nan}")

# Check for infinity
print(f"   math.isinf(math.inf) = {math.isinf(math.inf)}")
print(f"   math.isinf(100) = {math.isinf(100)}")

# Check for NaN
print(f"   math.isnan(math.nan) = {math.isnan(math.nan)}")


# ============================================================
# USING CONSTANTS IN CALCULATIONS
# ============================================================

print("\n4. USING CONSTANTS IN CALCULATIONS")

# Area of a circle
r = 7
area = math.pi * r ** 2
print(f"   Area of circle with radius {r}: {area:.2f}")

# Exponential growth
print(f"   e^2 = {math.e ** 2:.4f}")
print(f"   math.exp(2) = {math.exp(2):.4f}")

# Infinity in calculations
print(f"   math.inf + 5 = {math.inf + 5}")

Math constants key points:

  • math.pi — π (3.14159...)
  • math.tau — 2π (6.28318...)
  • math.e — Euler's number (2.71828...)
  • math.inf — Infinity
  • math.nan — Not a Number

Quick Check: What constant represents π in the math module? (Answer: math.pi)

Basic Mathematical Functions

2

Essential Functions for Everyday Math

These are the most commonly used math functions.

# Basic Mathematical Functions

import math

print("=" * 50)
print("BASIC MATHEMATICAL FUNCTIONS")
print("=" * 50)

# ============================================================
# SQUARE ROOT
# ============================================================

print("\n1. SQUARE ROOT")

# sqrt(x) - square root
numbers = [4, 9, 16, 25, 2]
for n in numbers:
    print(f"   sqrt({n}) = {math.sqrt(n):.4f}")

print(f"   sqrt(2) = {math.sqrt(2):.6f}")  # √2


# ============================================================
# POWER AND EXPONENT
# ============================================================

print("\n2. POWER AND EXPONENT")

# pow(x, y) - x raised to power y (same as x**y)
print(f"   pow(2, 3) = {math.pow(2, 3)}")
print(f"   pow(5, 2) = {math.pow(5, 2)}")

# exp(x) - e raised to power x
print(f"   exp(1) = {math.exp(1):.4f}")
print(f"   exp(2) = {math.exp(2):.4f}")


# ============================================================
# CEILING AND FLOOR
# ============================================================

print("\n3. CEILING AND FLOOR")

# ceil(x) - round up to nearest integer
# floor(x) - round down to nearest integer
values = [2.3, 2.7, -2.3, -2.7]
for v in values:
    print(f"   ceil({v}) = {math.ceil(v)}, floor({v}) = {math.floor(v)}")


# ============================================================
# FACTORIAL
# ============================================================

print("\n4. FACTORIAL")

# factorial(n) - n! (product of all numbers 1 to n)
for n in range(1, 6):
    print(f"   {n}! = {math.factorial(n)}")

# 10! = 3,628,800
print(f"   10! = {math.factorial(10)}")


# ============================================================
# ABSOLUTE VALUE
# ============================================================

print("\n5. ABSOLUTE VALUE")

# fabs(x) - absolute value (returns float)
print(f"   fabs(-5) = {math.fabs(-5)}")
print(f"   fabs(3.14) = {math.fabs(3.14)}")

# abs() is built-in and works too
print(f"   abs(-5) = {abs(-5)}")


# ============================================================
# COMBINATIONS AND PERMUTATIONS
# ============================================================

print("\n6. COMBINATIONS AND PERMUTATIONS")

# comb(n, k) - number of ways to choose k items from n
print(f"   comb(5, 2) = {math.comb(5, 2)}")  # C(5,2) = 10

# perm(n, k) - number of ways to arrange k items from n
print(f"   perm(5, 2) = {math.perm(5, 2)}")  # P(5,2) = 20

# 52 cards, choose 5 = 2,598,960 possible poker hands
print(f"   comb(52, 5) = {math.comb(52, 5)}")

Basic functions key points:

  • sqrt() — square root
  • pow() — power (x^y)
  • ceil() — round up
  • floor() — round down
  • factorial() — n!
  • comb() — combinations

Quick Check: How do you calculate the square root of a number? (Answer: math.sqrt(x))

Trigonometric Functions

3

Angles, Triangles, and Waves

The math module includes all standard trigonometric functions.

# Trigonometric Functions

import math

print("=" * 50)
print("TRIGONOMETRIC FUNCTIONS")
print("=" * 50)

# ============================================================
# DEGREES AND RADIANS CONVERSION
# ============================================================

print("\n1. DEGREES AND RADIANS")

# Convert degrees to radians
degrees = 180
radians = math.radians(degrees)
print(f"   {degrees}° = {radians:.4f} radians")

# Convert radians to degrees
radians = math.pi
degrees = math.degrees(radians)
print(f"   {radians:.4f} radians = {degrees}°")

# Common angles
for deg in [0, 30, 45, 60, 90, 180, 270, 360]:
    rad = math.radians(deg)
    print(f"   {deg}° = {rad:.4f} rad")


# ============================================================
# SINE, COSINE, TANGENT
# ============================================================

print("\n2. SINE, COSINE, TANGENT")

# sin(x) - sine of x (x in radians)
# cos(x) - cosine of x (x in radians)
# tan(x) - tangent of x (x in radians)

angles = [0, math.pi/6, math.pi/4, math.pi/3, math.pi/2]

print("   sin, cos, tan at various angles:")
for a in angles:
    deg = math.degrees(a)
    print(f"      {deg}°: sin={math.sin(a):.4f}, cos={math.cos(a):.4f}, tan={math.tan(a):.4f}")


# ============================================================
# INVERSE TRIGONOMETRY
# ============================================================

print("\n3. INVERSE TRIGONOMETRY")

# asin(x) - arcsin (inverse sine)
# acos(x) - arccos (inverse cosine)
# atan(x) - arctan (inverse tangent)

values = [0, 0.5, 1/math.sqrt(2), math.sqrt(3)/2, 1]
for v in values:
    print(f"   asin({v:.4f}) = {math.degrees(math.asin(v)):.1f}°")
    print(f"   acos({v:.4f}) = {math.degrees(math.acos(v)):.1f}°")
    print(f"   atan({v:.4f}) = {math.degrees(math.atan(v)):.1f}°")
    print()


# ============================================================
= HYPOTENUSE
# ============================================================

print("\n4. HYPOTENUSE")

# hypot(x, y) - sqrt(x² + y²) (Pythagorean theorem)
x, y = 3, 4
h = math.hypot(x, y)
print(f"   hypot({x}, {y}) = {h}")

# Distance between two points
x1, y1 = 0, 0
x2, y2 = 3, 4
distance = math.hypot(x2 - x1, y2 - y1)
print(f"   Distance between ({x1},{y1}) and ({x2},{y2}) = {distance}")


# ============================================================
# ATAN2 (angle from coordinates)
# ============================================================

print("\n5. ATAN2")

# atan2(y, x) - angle of point (x, y) from positive x-axis
points = [(1, 1), (0, 1), (-1, 1), (-1, -1)]
for x, y in points:
    angle = math.atan2(y, x)
    print(f"   atan2({y}, {x}) = {math.degrees(angle):.1f}°")

Trigonometry key points:

  • radians() — convert degrees to radians
  • degrees() — convert radians to degrees
  • sin(), cos(), tan() — trigonometric functions
  • asin(), acos(), atan() — inverse trigonometric functions
  • hypot() — hypotenuse (distance)

Quick Check: What function calculates the distance between two points? (Answer: math.hypot(dx, dy))

Logarithmic and Exponential Functions

4

Logarithms and Exponents

These functions are essential for scientific and financial calculations.

# Logarithmic and Exponential Functions

import math

print("=" * 50)
print("LOGARITHMIC AND EXPONENTIAL FUNCTIONS")
print("=" * 50)

# ============================================================
# EXPONENTIAL FUNCTION
# ============================================================

print("\n1. EXPONENTIAL FUNCTION")

# exp(x) - e^x
print(f"   exp(0) = {math.exp(0)}")  # e^0 = 1
print(f"   exp(1) = {math.exp(1):.6f}")  # e^1 = e
print(f"   exp(2) = {math.exp(2):.6f}")

# expm1(x) - e^x - 1 (more accurate for small x)
print(f"   expm1(1e-10) = {math.expm1(1e-10):.12f}")
print(f"   exp(1e-10) - 1 = {math.exp(1e-10) - 1:.12f}")


# ============================================================
# NATURAL LOGARITHM (base e)
# ============================================================

print("\n2. NATURAL LOGARITHM (base e)")

# log(x) - natural logarithm (base e)
numbers = [1, math.e, math.e**2, 10]
for n in numbers:
    print(f"   log({n:.2f}) = {math.log(n):.4f}")

# log1p(x) - log(1 + x) (more accurate for small x)
print(f"   log1p(1e-10) = {math.log1p(1e-10):.12f}")
print(f"   log(1 + 1e-10) = {math.log(1 + 1e-10):.12f}")


# ============================================================
# LOGARITHM WITH DIFFERENT BASES
# ============================================================

print("\n3. LOGARITHM WITH DIFFERENT BASES")

# log(x, base) - logarithm of x with given base
# log10(x) - logarithm base 10
# log2(x) - logarithm base 2

print(f"   log(100, 10) = {math.log(100, 10)}")
print(f"   log10(100) = {math.log10(100)}")
print(f"   log2(8) = {math.log2(8)}")

# Relationship between logs: log_a(b) = log(b) / log(a)
base = 10
value = 100
print(f"   log({value}, {base}) = log({value}) / log({base}) = {math.log(value) / math.log(base)}")


# ============================================================
# POWER FUNCTION
# ============================================================

print("\n4. POWER FUNCTION")

# pow(x, y) - x^y
print(f"   pow(2, 10) = {math.pow(2, 10)}")
print(f"   pow(10, 3) = {math.pow(10, 3)}")

# sqrt(x) = x^(1/2)
print(f"   sqrt(16) = {math.sqrt(16)}")


# ============================================================
# PRACTICAL APPLICATION: COMPOUND INTEREST
# ============================================================

print("\n5. PRACTICAL APPLICATION: COMPOUND INTEREST")

def compound_interest(principal, rate, time, comp_per_year):
    """Calculate compound interest"""
    amount = principal * math.pow(1 + rate/comp_per_year, comp_per_year * time)
    return amount

# $1000 at 5% for 10 years, compounded annually
principal = 1000
rate = 0.05
time = 10
amount = compound_interest(principal, rate, time, 1)
print(f"   ${principal} at {rate*100}% for {time} years = ${amount:.2f}")

Log/Exp key points:

  • exp() — e^x
  • log() — natural logarithm
  • log10() — base 10 logarithm
  • log2() — base 2 logarithm
  • pow() — x^y

Quick Check: What function calculates the natural logarithm? (Answer: math.log(x))

Advanced Functions

5

More Useful Math Functions

# Advanced Math Functions

import math

print("=" * 50)
print("ADVANCED MATH FUNCTIONS")
print("=" * 50)

# ============================================================
# GCD (Greatest Common Divisor)
# ============================================================

print("\n1. GCD (Greatest Common Divisor)")

# gcd(a, b) - greatest common divisor
print(f"   gcd(12, 18) = {math.gcd(12, 18)}")
print(f"   gcd(24, 36) = {math.gcd(24, 36)}")
print(f"   gcd(17, 19) = {math.gcd(17, 19)}")

# lcm - least common multiple (using gcd)
def lcm(a, b):
    return abs(a * b) // math.gcd(a, b)

print(f"   lcm(12, 18) = {lcm(12, 18)}")
print(f"   lcm(4, 6) = {lcm(4, 6)}")


# ============================================================
# TRUNCATE AND ROUND
# ============================================================

print("\n2. TRUNCATE AND ROUND")

# trunc(x) - truncate toward zero
values = [3.7, -3.7, 3.2, -3.2]
for v in values:
    print(f"   trunc({v}) = {math.trunc(v)}")

# round() is built-in (not in math module)
print(f"   round(3.7) = {round(3.7)}")
print(f"   round(3.2) = {round(3.2)}")


# ============================================================
# IS CLOSE (Floating Point Comparison)
# ============================================================

print("\n3. IS CLOSE (Floating Point Comparison)")

# isclose(a, b) - check if two numbers are close
a = 0.1 + 0.2
b = 0.3
print(f"   0.1 + 0.2 = {a}")
print(f"   a == b? {a == b}")
print(f"   isclose(a, b)? {math.isclose(a, b)}")

# With tolerance
print(f"   isclose(1.0, 1.0000001)? {math.isclose(1.0, 1.0000001)}")
print(f"   isclose(1.0, 1.000001)? {math.isclose(1.0, 1.000001)}")


# ============================================================
# COMBINATIONS AND PERMUTATIONS
# ============================================================

print("\n4. COMBINATIONS AND PERMUTATIONS")

# comb(n, k) - combinations (order doesn't matter)
print(f"   comb(10, 3) = {math.comb(10, 3)}")
print(f"   comb(52, 5) = {math.comb(52, 5)}")

# perm(n, k) - permutations (order matters)
print(f"   perm(10, 3) = {math.perm(10, 3)}")
print(f"   perm(5, 2) = {math.perm(5, 2)}")


# ============================================================
# FREXP AND LDEXP (Manipulate Exponents)
# ============================================================

print("\n5. FREXP AND LDEXP")

# frexp(x) - returns (mantissa, exponent) where x = mantissa * 2^exponent
x = 12.5
mantissa, exponent = math.frexp(x)
print(f"   frexp({x}) = ({mantissa}, {exponent})")
print(f"   {mantissa} * 2^{exponent} = {mantissa * (2 ** exponent)}")

# ldexp(mantissa, exponent) - reverse of frexp
y = math.ldexp(mantissa, exponent)
print(f"   ldexp({mantissa}, {exponent}) = {y}")


# ============================================================
# GAMMA AND LOG GAMMA
# ============================================================

print("\n6. GAMMA AND LOG GAMMA")

# gamma(x) - Gamma function (n! = gamma(n+1))
print(f"   gamma(5) = {math.gamma(5)}")  # (5-1)! = 4! = 24
print(f"   gamma(6) = {math.gamma(6)}")  # 5! = 120

# lgamma(x) - natural log of gamma (more efficient)
print(f"   lgamma(5) = {math.lgamma(5):.4f}")
print(f"   log(gamma(5)) = {math.log(math.gamma(5)):.4f}")

Advanced functions key points:

  • gcd() — greatest common divisor
  • lcm — least common multiple (use gcd)
  • isclose() — compare floating point numbers
  • comb() — combinations
  • perm() — permutations

Quick Check: How do you compare floating point numbers safely? (Answer: Use math.isclose())

Real-World Example

6

Building a Scientific Calculator

# Real-World Example: Scientific Calculator

import math
import sys

print("=" * 60)
print("SCIENTIFIC CALCULATOR")
print("=" * 60)

# ============================================================
# CALCULATOR CLASS
# ============================================================

class ScientificCalculator:
    """A scientific calculator using the math module"""
    
    def __init__(self):
        self.memory = 0
        self.history = []
    
    def add(self, a, b):
        result = a + b
        self._log(f"{a} + {b} = {result}")
        return result
    
    def subtract(self, a, b):
        result = a - b
        self._log(f"{a} - {b} = {result}")
        return result
    
    def multiply(self, a, b):
        result = a * b
        self._log(f"{a} * {b} = {result}")
        return result
    
    def divide(self, a, b):
        if b == 0:
            raise ValueError("Division by zero!")
        result = a / b
        self._log(f"{a} / {b} = {result:.4f}")
        return result
    
    def power(self, a, b):
        result = math.pow(a, b)
        self._log(f"{a}^{b} = {result:.4f}")
        return result
    
    def sqrt(self, a):
        if a < 0:
            raise ValueError("Cannot take square root of negative number")
        result = math.sqrt(a)
        self._log(f"sqrt({a}) = {result:.4f}")
        return result
    
    def sin(self, a, degrees=True):
        if degrees:
            a = math.radians(a)
        result = math.sin(a)
        self._log(f"sin({a:.2f}) = {result:.4f}")
        return result
    
    def cos(self, a, degrees=True):
        if degrees:
            a = math.radians(a)
        result = math.cos(a)
        self._log(f"cos({a:.2f}) = {result:.4f}")
        return result
    
    def tan(self, a, degrees=True):
        if degrees:
            a = math.radians(a)
        result = math.tan(a)
        self._log(f"tan({a:.2f}) = {result:.4f}")
        return result
    
    def log(self, a, base=math.e):
        if a <= 0:
            raise ValueError("Logarithm of non-positive number")
        result = math.log(a, base)
        self._log(f"log_{base}({a}) = {result:.4f}")
        return result
    
    def log10(self, a):
        return self.log(a, 10)
    
    def log2(self, a):
        return self.log(a, 2)
    
    def factorial(self, a):
        if a < 0 or not isinstance(a, int):
            raise ValueError("Factorial requires non-negative integer")
        result = math.factorial(a)
        self._log(f"{a}! = {result}")
        return result
    
    def _log(self, operation):
        self.history.append(operation)
    
    def get_history(self):
        return self.history
    
    def clear_history(self):
        self.history = []
    
    def show_help(self):
        print("\n   Available operations:")
        print("      add(a, b) - Addition")
        print("      subtract(a, b) - Subtraction")
        print("      multiply(a, b) - Multiplication")
        print("      divide(a, b) - Division")
        print("      power(a, b) - Power (a^b)")
        print("      sqrt(a) - Square root")
        print("      sin(a) - Sine (degrees)")
        print("      cos(a) - Cosine (degrees)")
        print("      tan(a) - Tangent (degrees)")
        print("      log(a, base) - Logarithm")
        print("      log10(a) - Log base 10")
        print("      log2(a) - Log base 2")
        print("      factorial(a) - Factorial")
        print("      get_history() - Show history")
        print("      clear_history() - Clear history")
        print("      show_help() - Show this help")


# ============================================================
# DEMONSTRATION
# ============================================================

print("\n1. CREATING CALCULATOR")
calc = ScientificCalculator()

print("\n2. BASIC OPERATIONS")
print(f"   add(10, 5) = {calc.add(10, 5)}")
print(f"   subtract(10, 5) = {calc.subtract(10, 5)}")
print(f"   multiply(10, 5) = {calc.multiply(10, 5)}")
print(f"   divide(10, 5) = {calc.divide(10, 5)}")
print(f"   power(2, 10) = {calc.power(2, 10)}")

print("\n3. TRIGONOMETRY")
print(f"   sin(30) = {calc.sin(30):.4f}")
print(f"   cos(60) = {calc.cos(60):.4f}")
print(f"   tan(45) = {calc.tan(45):.4f}")

print("\n4. LOGARITHMS")
print(f"   log(100, 10) = {calc.log(100, 10)}")
print(f"   log10(1000) = {calc.log10(1000)}")
print(f"   log2(8) = {calc.log2(8)}")

print("\n5. OTHER FUNCTIONS")
print(f"   sqrt(144) = {calc.sqrt(144)}")
print(f"   factorial(5) = {calc.factorial(5)}")

print("\n6. HISTORY")
print("   Operations performed:")
for i, op in enumerate(calc.get_history(), 1):
    print(f"      {i}. {op}")

print("\n7. ADVANCED CALCULATIONS")
# Calculate distance between two points
def distance(x1, y1, x2, y2):
    return math.hypot(x2 - x1, y2 - y1)

dist = distance(0, 0, 3, 4)
print(f"   Distance between (0,0) and (3,4) = {dist}")

# Calculate area of a circle
def circle_area(radius):
    return math.pi * radius ** 2

area = circle_area(5)
print(f"   Area of circle with radius 5 = {area:.2f}")

# Calculate compound interest
def compound_interest(principal, rate, time, comp_per_year):
    return principal * math.pow(1 + rate/comp_per_year, comp_per_year * time)

amount = compound_interest(1000, 0.05, 10, 12)
print(f"   $1000 at 5% for 10 years (monthly) = ${amount:.2f}")

print("\n" + "=" * 60)
print("KEY TAKEAWAYS:")
print("=" * 60)
print("""
- math module provides all essential mathematical functions
- Use radians for trigonometric functions
- isclose() for safe floating point comparison
- pow() and sqrt() for power operations
- log() and exp() for logarithmic operations
- Perfect for scientific and financial calculations
""")

Real-world example key points:

  • Scientific calculator — practical application of math module
  • Trigonometry — sin, cos, tan with degree support
  • Logarithms — log with different bases
  • Distance calculation — hypot() function
  • Compound interest — pow() for financial calculations

Quick Check: What function would you use to calculate the distance between two points? (Answer: math.hypot(dx, dy))

Best Practices

7

Using Math Module Effectively

# Best Practices for Math Module

import math

print("=" * 60)
print("BEST PRACTICES FOR MATH MODULE")
print("=" * 60)

# ============================================================
# 1. USE ISCLOSE FOR FLOATING POINT COMPARISON
# ============================================================

print("\n1. USE ISCLOSE FOR FLOATING POINT COMPARISON")

# Good - using isclose
a = 0.1 + 0.2
b = 0.3
if math.isclose(a, b):
    print(f"   {a} is close to {b}")

# Bad - using == (can fail due to floating point precision)
if a == b:
    print("   This might not print")

# ============================================================
# 2. USE RADIANS FOR TRIGONOMETRY
# ============================================================

print("\n2. USE RADIANS FOR TRIGONOMETRY")

# Good - convert to radians
angle_deg = 45
angle_rad = math.radians(angle_deg)
sin_val = math.sin(angle_rad)
print(f"   sin({angle_deg}°) = {sin_val:.4f}")

# Bad - using degrees directly (wrong!)
# sin_val = math.sin(45)  # This would be wrong

# ============================================================
# 3. USE POW OR ** FOR POWER
# ============================================================

print("\n3. USE POW OR ** FOR POWER")

# Both work, choose what's clearer
print(f"   math.pow(2, 10) = {math.pow(2, 10)}")
print(f"   2 ** 10 = {2 ** 10}")

# ============================================================
# 4. CHECK FOR VALID INPUT
# ============================================================

print("\n4. CHECK FOR VALID INPUT")

def safe_sqrt(x):
    if x < 0:
        raise ValueError("Cannot take square root of negative number")
    return math.sqrt(x)

try:
    result = safe_sqrt(-1)
except ValueError as e:
    print(f"   Error: {e}")

# ============================================================
# 5. USE LOG WITH BASE FOR CLARITY
# ============================================================

print("\n5. USE LOG WITH BASE FOR CLARITY")

# Good - explicit base
print(f"   math.log(100, 10) = {math.log(100, 10)}")

# Also good - use specific function
print(f"   math.log10(100) = {math.log10(100)}")

# ============================================================
# 6. COMBINE WITH OTHER MODULES
# ============================================================

print("\n6. COMBINE WITH OTHER MODULES")

import random

# Generate a random angle and calculate its sine
random_angle = random.uniform(0, 360)
sin_value = math.sin(math.radians(random_angle))
print(f"   sin({random_angle:.1f}°) = {sin_value:.4f}")

# ============================================================
# 7. SUMMARY
# ============================================================

print("\n" + "=" * 60)
print("BEST PRACTICES SUMMARY")
print("=" * 60)
print("""
- Use isclose() for floating point comparisons
- Always use radians for trig functions
- Check input values for validity
- Use explicit base with log()
- Combine math module with other modules
- Use constants (pi, e) directly
- Document your calculations
""")

Best practices summary:

  • Use isclose() — for safe floating point comparison
  • Use radians — for trigonometric functions
  • Check input — validate before using functions
  • Use explicit base — with log() for clarity
  • Combine modules — math works well with random, etc.

Quick Check: How should you compare floating point numbers? (Answer: Use math.isclose())

Try It Yourself

Experiment with the math module in the editor below.

Loading Pyodide... 0%
Python Code Editor
==================================================
MATH MODULE - PRACTICE
==================================================

1. CONSTANTS
pi = 3.141593
e = 2.718282
tau = 6.283185

2. BASIC FUNCTIONS
sqrt(16) = 4.0
ceil(3.7) = 4
floor(3.7) = 3
factorial(5) = 120
pow(2, 10) = 1024.0

3. TRIGONOMETRY
sin(45°) = 0.7071
cos(45°) = 0.7071
tan(45°) = 1.0000
degrees(pi) = 180.0

4. LOGARITHMS
log(e) = 1.0
log(100, 10) = 2.0
log10(1000) = 3.0
log2(8) = 3.0

5. PRACTICAL CALCULATIONS
Area of circle (r=5): 78.54
Distance between (0,0) and (3,4): 5.0
$1000 at 5.0% for 10 years = $1628.89
🏆

You've Got It!

You now understand the math module in Python. You know how to use constants, basic functions, trigonometry, logarithms, and advanced mathematical operations.

Quick Quiz

Test what you've learned:

1. How do you calculate the square root of a number?
2. What constant represents π?
3. What function converts degrees to radians?
4. How do you calculate 5! (5 factorial)?
5. How should you compare floating point numbers?

Frequently Asked Questions

What is the math module in Python? ▼

The math module provides a comprehensive set of mathematical functions and constants. It includes functions for basic arithmetic, trigonometry, logarithms, exponentials, and more.

What's the difference between math.pow() and **? ▼

math.pow() always returns a float, while ** can return an integer if both operands are integers. math.pow() is also slightly faster for floating point calculations. Use ** for clarity and math.pow() for consistency when you need a float.

Why does 0.1 + 0.2 != 0.3? ▼

This is due to floating point precision. Computers can't represent some decimal numbers exactly in binary. Use math.isclose() to compare floating point numbers safely.

How do I calculate the distance between two points? ▼

Use math.hypot(x2-x1, y2-y1). This calculates sqrt((x2-x1)² + (y2-y1)²) efficiently and accurately.

What's the difference between log() and log10()? ▼

math.log(x) is the natural logarithm (base e). math.log10(x) is the base 10 logarithm. Use math.log(x, base) for other bases.

Can I use math module with complex numbers? ▼

No, the math module works with real numbers only. For complex numbers, use the cmath module, which provides similar functions for complex numbers.

Where to Go From Here

Now that you understand the math module, check out these related topics:

Random Module

Learn about generating random numbers and choices.

Learn More →

Datetime Module

Learn about working with dates and times.

Learn More →

Collections Module

Learn about specialized container data types.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Python Lists and Dictionaries Interview Questions
  • Python OOP Interview Questions
  • SQL Set Operators Interview Questions
Previous: Random Next: Standard Library Assignments →