Python operators
doing things to values
2025-11-03 18:04
// updated 2025-11-03 18:49
// updated 2025-11-03 18:49
Operators simply do things to values (which, as we have learned, oftentimes live inside variables):
- arithmetic
- e.g. addition, subtraction, multiplication, division, remainder
- assignment
- e.g. assignment, increment, decrement
- comparison
- e.g. equality, inequality, greater than (or equal to), lesser than (or equal to)
- logical
- e.g. and (all values are true), or (one of the values is true)
Let's have a look some operators...
Arithmetic operators
These operators try to alter values with an integer or float type:
| Operator in Python | Description | Code example |
|---|---|---|
| + | Addition | x + y |
| - | Subtraction | x - y |
| * | Multiplication | x * y |
| ** | Power | x ** y |
| / | Division | x / y |
| // | Division (rounded to lowest integer) | x // y |
| % | Modulo | x % y |
An example of some of the less obvious operators:
x = 14
y = 3
print(x ** y) # 14^3 = 2744
print(x // y) # floor(14/3) = 4
print(x % y) # 2
# note: 14/3 leaves a remainder of 2Assignment operators
These operators put values into some named piece of memory (basically the same thing as declaring a variable!) In addition, they may also perform an additional arithmetic operation with a shorter syntax:
x = 2
x += 4
print(x)
# 6Note that the second line of the above is equivalent to:
x = x + 4Other assignment operators also include:
x = 2
x -= 1
print(x)
# 1
# recall: (2 - 1 == 1)
x *= 8
print(x)
# 8
# recall: (1 * 8 == 8)
x /= 4
print(x)
# 2
# recall: (8 / 4 == 2)
x %= 1
print(x)
# 0
# recall: (2 % 1 == 0)Comparison operators
When we want to look at two different values, we can use these operators:
x = 3
y = 4
print(x == y)
# false (x is not "equal" to y)
print (x != y)
# true (x "is not equal" to y)
print(x > y)
# false (x is not "greater" than y)
print (x < y)
# true (x is "less" than y)
print (x >= y)
# false (x is not "greater than or equal" to y)
print (x <= y)
# true (x is "less than or equal" to y)Logical operators
When we want to evaluate multiple comparisons or conditions, we can use things like "and" and "or" and "not":
x = 9
y = 15
z = 4
print(x > 3 and y > 10)
# True
print(x < 3 and y > 10)
# False (x is not "less than 3")
print(x > 3 or y > 10)
# True (both are true but only one of them needs to be)
print(x > 3 or y > 10)
# True (only y > 10 needs to e true)
print(not(z > 2))
# False (z is not "not greater than" 2, i.e. it is!)