Home/Blog/Python Math Operators | Complete Guide
Python

Python Math Operators | Complete Guide

Master addition, subtraction, multiplication, division, exponents, and more with clear examples

Python Math Operators | Complete Guide

Basic Math Operators

DescriptionOperatorExample
Add+1+2=3
Subtract3-2=1
Multiply*2*3=6
Divide/6/3=2
Floor Division//5//2=2
Remainder%5%2=1
Exponent**2**3=8

Order of Operations (PEMDAS)

The order of operation is crucial because it can significantly affect the outcome of your equation. Remember PEMDAS: Parentheses, Exponents, Multiplication, Division, Addition, Subtraction.

# Without parentheses: multiplication first
result1 = 1 + 2 * 3  # Result: 7 (not 9)

# With parentheses: addition first
result2 = (1 + 2) * 3  # Result: 9

Addition and Subtraction

x = 2
y = 4

# Basic operations
print(x + y)  # Output: 6
print(y - x)  # Output: 2

# Increment and decrement
x += 1  # Same as x = x + 1
print(x)  # Output: 3

y -= 2  # Same as y = y - 2
print(y)  # Output: 2

Exponents and Roots

Exponents multiply a number by itself multiple times. Roots are the opposite operation, finding what number multiplied by itself gives the original number.

# Exponents
print(2 ** 3)  # Output: 8 (2 * 2 * 2)
print(5 ** 2)  # Output: 25 (5 * 5)

# Square roots
print(4 ** (1/2.0))   # Output: 2.0
print(9 ** (1/2.0))   # Output: 3.0

# Cube roots
print(27 ** (1/3.0))  # Output: 3.0

Important: For roots, use (1/2.0) instead of (1/2) to ensure you get a float result, not an integer.

Frequently Asked Questions

Find answers to common questions

Python 3 changed division: / always returns float (true division), // returns int (floor division). Examples: 7 / 2 = 3.5, 7 // 2 = 3 (floors down). Critical for: pagination (pages = total_items // items_per_page), array indexing (index = position // chunk_size), splitting work (batches = dataset_size // batch_size). Gotcha: // floors toward negative infinity, not zero: -7 // 2 = -4 (not -3). For rounding toward zero: int(7 / 2) or math.trunc(7 / 2). Performance: // slightly faster for integers (microseconds difference—negligible). Python 2 difference: / did integer division for ints (7 / 2 = 3), breaking change in Python 3. Use /: normal math, scientific calculations, user-facing numbers. Use //: discrete quantities, counting, indexing. Pair with modulo: divmod(7, 2) returns (3, 1) efficiently. Type safety: 7 // 2 = 3 (int), 7 / 2 = 3.5 (float), maintain int for discrete values.

Automate Your IT Operations

Leverage automation to improve efficiency, reduce errors, and free up your team for strategic work.