Operators in Python
Operators in Python
Section titled “Operators in Python”Introduction
Section titled “Introduction”Operators are special symbols that perform operations on values and variables.
Arithmetic Operators
Section titled “Arithmetic Operators”a, b = 17, 5
print(a + b) # 22 — Additionprint(a - b) # 12 — Subtractionprint(a * b) # 85 — Multiplicationprint(a / b) # 3.4 — True Division (always float)print(a // b) # 3 — Floor Divisionprint(a % b) # 2 — Modulus (remainder)print(a ** b) # 1419857 — ExponentiationComparison Operators
Section titled “Comparison Operators”a, b = 10, 20print(a == b) # Falseprint(a != b) # Trueprint(a > b) # Falseprint(a < b) # Trueprint(a >= b) # Falseprint(a <= b) # True
# Chainingx = 15print(10 < x < 20) # True — Pythonic!Logical Operators
Section titled “Logical Operators”print(True and True) # Trueprint(True or False) # Trueprint(not True) # False
# Short-circuit evaluationprint(False and expensive_function()) # False — function never called!Identity Operators
Section titled “Identity Operators”a = [1, 2, 3]b = [1, 2, 3]c = a
print(a == b) # True — same valueprint(a is b) # False — different objectsprint(a is c) # True — same objectMembership Operators
Section titled “Membership Operators”fruits = ["apple", "banana", "cherry"]print("banana" in fruits) # Trueprint("mango" not in fruits) # TrueBitwise Operators
Section titled “Bitwise Operators”a = 0b1010 # 10b = 0b1100 # 12
print(a & b) # 8 — ANDprint(a | b) # 14 — ORprint(a ^ b) # 6 — XORprint(~a) # -11 — NOTprint(a << 1) # 20 — Left shiftprint(a >> 1) # 5 — Right shiftOperator Precedence
Section titled “Operator Precedence”| Priority | Operator |
|---|---|
| 1 | () |
| 2 | ** |
| 3 | *, /, //, % |
| 4 | +, - |
| 5 | Comparisons (==, <, >, in, is) |
| 6 | not |
| 7 | and |
| 8 | or |
Walrus Operator (:=) — Python 3.8+
Section titled “Walrus Operator (:=) — Python 3.8+”data = [1, 2, 3, 4, 5]if (n := len(data)) > 3: print(f"List has {n} elements")Why It Matters
Section titled “Why It Matters”Operators are the building blocks of all program logic. Understanding precedence and short-circuit evaluation prevents subtle bugs.
Common Mistakes
Section titled “Common Mistakes”- Using
=instead of==in comparisons - Using
isfor value comparison (use==instead!) - Not understanding short-circuit evaluation
Interview Questions
Section titled “Interview Questions”Q1: What’s the difference between is and ==?
A: == compares values; is checks object identity (same memory location).
Q2: What is short-circuit evaluation?
A: Python’s and/or operators stop evaluating once the result is determined. False and x → x never evaluated.
Practice Exercises
Section titled “Practice Exercises”- Check if a number is divisible by both 3 and 7.
- Use bitwise operators to check if a number is even.
- Demonstrate short-circuit evaluation.