Topic 9 of 58
Logical & Bitwise Operators
Overview
Logical operators (and, or, not) evaluate boolean conditions and govern control flow. They utilize 'short-circuit evaluation' for efficiency. Bitwise operators (&, |, ^, ~, <<, >>) operate at the lowest level, manipulating individual binary bits of integers. While rarely used in high-level web apps, bitwise operations are critical for cryptography, low-level systems, and specific algorithmic challenges.
Syntax
python
# Logical Operators
x, y = True, False
print(x and y) # False (Both must be True)
print(x or y) # True (At least one must be True)
print(not x) # False (Inverts the boolean)
# Bitwise Operators
a = 5 # Binary: 0101
b = 3 # Binary: 0011
print(a & b) # 1 (0001) - AND: bit is 1 if both are 1
print(a | b) # 7 (0111) - OR: bit is 1 if either is 1
print(a ^ b) # 6 (0110) - XOR: bit is 1 if bits differ
print(a << 1) # 10 (1010) - Left Shift: moves bits left by 1Common Pitfalls
- Using
&instead ofandfor boolean logic. Bitwise operators have higher precedence than comparison operators, which can completely break anifstatement. - Forgetting how short-circuiting works. In
A or B, if A is Truthy, B is completely ignored and never executed.
Interview Questions
Q:
How can you multiply an integer by 2 using bitwise operators?
A:
By using the left shift operator (<<). Shifting bits left by 1 place effectively multiplies the number by 2 (x << 1). Shifting right divides by 2.
Real-World Example
Using short-circuit evaluation to safely check nested properties without throwing errors.
example
python
user_data = None
# If user_data is None, the 'and' operator short-circuits.
# It immediately returns False without ever evaluating user_data.get(),
# preventing a catastrophic AttributeError.
if user_data and user_data.get("is_admin"):
print("Welcome, Administrator")
else:
print("Access Denied")Check Your Knowledge
Test your understanding of Logical & Bitwise Operators with these quick questions.