To do math in python, you need to know these two types:
- int: Whole numbers (1, 10, -5).
- float: Numbers with decimals (2.0, 1.5, -0.1).
Arithmetic Operators
Python handles basic math mostly how you’d expect, but there are a few specific behaviors to watch out for.
Addition (+) & Subtraction (-)
revenue = 50
costs = 35
profit = revenue - costs
print(profit) # 15
Multiplication (*) & Division (/)
In Python, regular division always returns a float (a number with a decimal), even if the result is a whole number.
print(10 * 3) # 30
print(10 / 5) # 2.0
print(10 / 3) # 3.333...
In older versions of Python (Python 2), 10 / 3 would give you 3. In Python 3, it gives you 3.333....
Exponent (**)
This raises a number to a power.
print(3 ** 2) # 9 (3 squared)
Floor Division (//)
This divides two numbers and rounds down to the nearest whole number. If you use it with a float, it still rounds down but returns a .0.
print(5 // 3) # 1
print(7.0 // 2) # 3.0
Modulo (%)
This gives you the remainder of a division. It is most commonly used to check if a number is even or odd. If num % 2 == 0, the number is even.
print(11 % 3) # 2 (3 goes into 11 three times (3*3=9), leaving 2 left over (11-9=2))
Order of Operations
Python follows PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction). Use parentheses () if you want to force a specific order.
Assignment Operators
You know = assigns a value. But if you want to update a variable based on its current value, you can use shorthand.
Instead of writing num = num + 5, you write:
num = 10
num += 5 # 15
This works for all the operators we just covered:
+=,-=(Add/Subtract)*=,/=(Multiply/Divide)**=,//=(Power/Floor Div)
The “Missing” Operators
If you are coming from Java, C++, or JavaScript, you might look for ++ or --.
Python does not have these.
x = 1
# THIS WILL CRASH
x++
You must use x+=1. This is actually a good thing, as it keeps the code more readable and avoids the confusion between “pre-increment” and “post-increment” logic found in other languages.