Operators
Arithmetic, comparison, logical, and assignment operators in Python.
Arithmetic Operators
- + (addition), - (subtraction), * (multiplication)
- / (division), // (floor division), % (modulus)
- ** (exponentiation)
x = 10
y = 3
print(x + y) # 13
print(x - y) # 7
print(x * y) # 30
print(x / y) # 3.333...
print(x // y) # 3 (floor division)
print(x % y) # 1 (remainder)
print(x ** y) # 1000 (10^3)
Comparison Operators
- == (equal), != (not equal)
- > (greater), < (less)
- >= (greater or equal), <= (less or equal)
- Return True or False
a = 5
b = 10
print(a == b) # False
print(a != b) # True
print(a < b) # True
print(a > b) # False
print(a <= 5) # True
print(b >= 10) # True
Logical Operators
- and: Both conditions must be True
- or: At least one condition must be True
- not: Reverses the boolean value
x = 5
y = 10
print(x > 0 and y > 0) # True
print(x > 10 or y > 5) # True
print(not(x > 10)) # True
# Combining conditions
age = 20
if age >= 18 and age < 65:
print("Working age")
Assignment Operators
- = (assign), += (add and assign), -= (subtract and assign)
- *= (multiply and assign), /= (divide and assign)
- Shorthand for common operations
x = 10
x += 5 # Same as: x = x + 5
print(x) # 15
x -= 3 # Same as: x = x - 3
print(x) # 12
x *= 2 # Same as: x = x * 2
print(x) # 24
x /= 4 # Same as: x = x / 4
print(x) # 6.0