How to Use Python Math Operators
Master addition, subtraction, multiplication, division, exponents, and more with clear examples
Understanding Python math operators is very important. You use these operators throughout the Python language whether it be concatenating strings, doing basic algebra, complex calculus, or delving into data science.
Basic Math Operators
Description | Operator | Example |
---|---|---|
Add | + | 1+2=3 |
Subtract | – | 3-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.
Elevate Your IT Efficiency with Expert Solutions
Transform Your Technology, Propel Your Business
Unlock advanced technology solutions tailored to your business needs. At InventiveHQ, we combine industry expertise with innovative practices to enhance your cybersecurity, streamline your IT operations, and leverage cloud technologies for optimal efficiency and growth.