Operators perform operations on variables and values. Python has 7 operator types.
1. Arithmetic Operators
Addition +
5 + 3 # 8
Subtraction -
10 - 2 # 8
Multiplication *
4 * 3 # 12
Division /
10 / 2 # 5.0 (float)
Modulus %
10 % 3 # 1 (remainder)
Exponentiation **
2 ** 3 # 8
Floor Division //
10 // 3 # 3 (integer division)
Exercise 1:
Calculate:
(15 // 4) + (2 ** 3)- The area of a circle with radius 7 (πr²)
import math
print((15 // 4) + (2 ** 3)) # 11
print(math.pi * 7 ** 2) # 153.93804
2. Comparison Operators
Equal ==
5 == 5 # True
Not Equal !=
5 != 3 # True
Greater Than >
10 > 5 # True
Less Than <
10 < 5 # False
Greater/Equal >=
10 >= 10 # True
Less/Equal <=
5 <= 3 # False
Interactive Demo
5 == 3 # False
3. Logical Operators
AND and
True if both conditions are True
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
OR or
True if at least one condition is True
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
NOT not
Inverts the boolean value
| A | not A |
|---|---|
| True | False |
| False | True |
Exercise 2:
Given age = 25 and is_member = True, evaluate:
age > 18 and is_memberage < 21 or not is_member
age = 25
is_member = True
print(age > 18 and is_member) # True
print(age < 21 or not is_member) # False
Operator Cheat Sheet
| Type | Operators | Examples |
|---|---|---|
| Arithmetic | + - * / % ** // |
5 + 3 → 8 |
| Comparison | == != > < >= <= |
5 > 3 → True |
| Logical | and or not |
True and False → False |
| Assignment | = += -= *= /= |
x += 5 (x = x + 5) |
| Membership | in not in |
"a" in ["a","b"] → True |