Arithmetic Operators
Python provides the standard math operators we are familiar with, plus a few others that make common calculations much faster.
Basic Arithmetic
Python behaves like a calculator. It follows the standard order of operations (PEMDAS).
a = 15
b = 7
print(a + b) # Addition (22)
print(a - b) # Subtraction (8)
print(a * b) # Multiplication (105)
22
8
105
Unique Python Operators
If we're coming from C, we'll find these very handy for quick math.
Floor Division Vs Standard Division
In Python, standard division (/) always results in a float (e.g., 10 / 2 = 5.0).
Use floor division (//) when we care only about the whole number part and want to chop off the decimal.
print(15 / 7) # 2.1428... (Standard)
print(15 // 7) # 2 (Floor)
2.142857142857143
2
Exponentiation and Modulo
- Raising one number to the power of another (
**) is built directly into the language, replacing the need forpow(). - The modulo operator (
%) gives us the remainder of a division.
print(5 ** 3) # 125 (5 to the power of 3)
print(15 % 7) # 1 (Remainder)
125
1
Shorthand Operators
We can modify a variable's value in place using shorthand.
counter = 10
counter += 5 # Same as counter = counter + 5
counter -= 2 # Same as counter = counter - 2
print(counter) # Result: 13
13
Worth Mentioning: Identity and Membership
- is / is not: Checks if two variables point to the same memory object (Identity).
- in / not in: Checks if a value exists within a collection (Membership).
x = [1, 2, 3]
y = [1, 2, 3]
# Identity: Are they the same object?
print(x is y) # False (they are separate lists)
# Membership: Is 1 inside the list?
print(1 in x) # True
Output:
False
True