Operators in Python

Module 1 • Session 06 • Allocation: 1 Contact Hr

Arithmetic & Bitwise Short-Circuiting Identity vs Equality Operator Precedence

Operators are construct symbols that instruct Python's interpreter to execute specific mathematical, relational, bitwise, or logical transformations on operands. Python groups operators into distinct functional categories, each backed by special dunder methods (e.g., __add__, __eq__) under the hood.

1. Arithmetic Operators and Floor Division Mechanics

Arithmetic operators handle mathematical computations on numeric operands (int, float, complex).

Operator Name Example Expression Output Result
+ Addition 15 + 4 19
- Subtraction 15 - 4 11
* Multiplication 15 * 4 60
/ True Division 15 / 4 3.75 (Always returns float)
// Floor Division 15 // 4 vs -15 // 4 3 vs -4 (Rounds down)
% Modulus (Remainder) 15 % 4 3
** Exponentiation 2 ** 4 16
Floor Division Edge Case: Floor division (//) rounds results down toward negative infinity (the mathematical floor). For positive operands 15 // 4 = 3, but for negative values -15 // 4 = -4.
# True Division vs Floor Division vs Modulus a, b = 17, 5 print(f"True Division (a / b) : {a / b}") # Output: 3.4 print(f"Floor Division (a // b): {a // b}") # Output: 3 print(f"Modulus (a % b) : {a % b}") # Output: 2 # Negative Floor Division Behavior print(f"-17 // 5 : {-17 // 5}") # Output: -4 print(f"-17 % 5 : {-17 % 5}") # Output: 3 (Formula: r = a - (b * (a // b)))

2. Comparison (Relational) & Identity Operators

Comparison operators evaluate relative magnitude and return boolean values (True or False). Identity operators compare object memory references rather than values.

Category Operator Description Example Check
Comparison ==, != Value equality and inequality [1, 2] == [1, 2] (True)
Comparison >, <, >=, <= Magnitude ordering 10 >= 5 (True)
Identity is Same memory identity address a is b (Checks id(a) == id(b))
Identity is not Different memory identity addresses x is not None
# Value Equality (==) vs Memory Identity (is) list_1 = [10, 20, 30] list_2 = [10, 20, 30] list_3 = list_1 print(f"list_1 == list_2 : {list_1 == list_2}") # True (Contents are identical) print(f"list_1 is list_2 : {list_1 is list_2}") # False (Distinct objects in memory) print(f"list_1 is list_3 : {list_1 is list_3}") # True (Point to identical memory reference) # Correct Idiomatic Null Check value = None print(value is None) # Preferred over 'value == None'

3. Logical Operators & Short-Circuit Evaluation

Python provides and, or, and not for boolean operations. Logical operators use **short-circuit evaluation**: evaluation stops as soon as the outcome is finalized.

  • A and B: Returns A if A is falsy; otherwise returns B.
  • A or B: Returns A if A is truthy; otherwise returns B.
  • not A: Returns True if A is falsy; otherwise returns False.
def side_effect_function(): print("--> Function Executed!") return True # Short-Circuiting with 'or' # Since the left operand is True, the right function is NEVER evaluated! print("Evaluating 'True or side_effect_function()':") result_1 = True or side_effect_function() # Short-Circuiting with 'and' # Since the left operand is False, execution stops immediately! print("\nEvaluating 'False and side_effect_function()':") result_2 = False and side_effect_function()

4. Bitwise Operators

Bitwise operators act on integers at the binary bit level. Python integers are represented in **Two's Complement** format with arbitrary precision.

Operator Name Binary Expression Output Value
& Bitwise AND 12 & 10 (1100 & 1010) 8 (1000)
| Bitwise OR 12 | 10 (1100 | 1010) 14 (1110)
^ Bitwise XOR 12 ^ 10 (1100 ^ 1010) 6 (0110)
~ Bitwise NOT ~12 (Inverts bits) -13 (Formula: -(x + 1))
<< Left Shift 5 << 2 (Shift left 2 bits) 20 (Multiplies by 2**2)
>> Right Shift 20 >> 2 (Shift right 2 bits) 5 (Floor divides by 2**2)

5. Membership Operators & Operator Precedence

Membership operators (in, not in) test whether a target sequence contains a specified element.

Operator Precedence Hierarchy (Highest to Lowest)

  1. () — Parentheses grouping
  2. ** — Exponentiation
  3. +x, -x, ~x — Unary plus, minus, bitwise NOT
  4. *, /, //, % — Multiplication, divisions, modulus
  5. +, - — Addition and Subtraction
  6. <<, >> — Bitwise shifts
  7. & — Bitwise AND
  8. ^ — Bitwise XOR
  9. | — Bitwise OR
  10. ==, !=, >, <, is, in — Comparison, Identity, Membership
  11. not — Logical NOT
  12. and — Logical AND
  13. or — Logical OR
# Precedence & Evaluation Order Example res = 10 + 2 * 3 ** 2 # Step 1: Exponentiation => 3 ** 2 = 9 # Step 2: Multiplication => 2 * 9 = 18 # Step 3: Addition => 10 + 18 = 28 print(f"Calculated Result: {res}") # Output: 28 # Membership In Dictionaries (Checks keys by default) user_data = {"name": "Alice", "role": "Admin"} print("role" in user_data) # True print("Admin" in user_data) # False (Checks keys, not values) print("Admin" in user_data.values()) # True

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Bitwise Flag Permission System

Write script logic using bitwise operators (&, |, ~) to toggle, check, and revoke user access permissions (READ=1, WRITE=2, EXECUTE=4).

Challenge 2: Short-Circuit Guard Validator

Implement a safe dictionary lookup expression using logical short-circuiting to prevent KeyError and TypeError exceptions without using try-except blocks.

Challenge 3: Walrus Operator Expression

Use the assignment expression operator (:=) inside a while loop to read user inputs dynamically until a specific keyword is supplied.

⚡ Interactive Sandbox (Python Operator Tester)
Console Output:
Click "Run Code" above to execute interactive input scripts...

📝 Knowledge Check Quiz

1. What is the output of `-19 // 5` in Python?
2. What does expression `a is b` evaluate?
3. What is the value of `10 << 2`?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)