Operators (Arithmetic, Comparison, Logical)
Operators perform operations on values — math, comparisons, and logic. Python supports arithmetic, comparison, logical, assignment, and identity operators. Mastering these is essential for every program you write.
Python Operators
- + — Addition: 5 + 3 = 8
- - — Subtraction: 10 - 4 = 6
- * — Multiplication: 3 * 4 = 12
- / — Division (float): 10 / 3 = 3.333...
- // — Floor division (int): 10 // 3 = 3
- % — Modulus (remainder): 10 % 3 = 1
- ** — Power: 2 ** 8 = 256
- Comparison: ==, !=, >, <, >=, <= → return True/False
- Logical: and, or, not → combine conditions
Operators Code
a = 10
b = 3
# Arithmetic operators
print("Addition:", a + b) # 13
print("Subtraction:", a - b) # 7
print("Multiplication:", a * b) # 30
print("Division:", a / b) # 3.333...
print("Floor division:", a // b) # 3
print("Remainder:", a % b) # 1
print("Power:", a ** 2) # 100
# Comparison operators (return True/False)
print(10 > 5) # True
print(10 == 10) # True
print(10 != 5) # True
print(10 <= 5) # False
# Logical operators
print(True and False) # False
print(True or False) # True
print(not True) # False
# Practical example
age = 20
has_id = True
can_enter = age >= 18 and has_id
print("Can enter:", can_enter) # TrueTry It Yourself: Calculator
Tip
Tip
Use % (modulo) to check even/odd: n % 2 == 0 means even. Use // for integer division when you need whole numbers. Use ** for powers instead of importing math.
Everything in Python is an object — use type() to check
Common Mistake
Warning
Don't confuse = (assignment) with == (comparison). x = 5 assigns, x == 5 compares. Writing if x = 5: is a SyntaxError in Python (unlike C where it's a common bug).
Practice Task
Note
Build a calculator: (1) Store two numbers in variables. (2) Print all operations: +, -, *, /, //, %, **. (3) Check if the first number is even using %. (4) Compare the two numbers with >, <, ==.
Quick Quiz
Key Takeaways
- Operators perform operations on values — math, comparisons, and logic.
- + — Addition: 5 + 3 = 8
- — Subtraction: 10 - 4 = 6
- — Multiplication: 3 * 4 = 12