Sharpen your Python skills by identifying and correcting mistakes in operator usage. This hands-on practice guide covers common errors in arithmetic, logical, and comparison operators with clear solutions.
Topic: operators
Fix the incorrect exponentiation operation:
result = 2 ^ 3
print(result)
Hint: 💡 Python uses a different operator for exponentiation than some other languages.
Issue: The caret (^) is a bitwise XOR operator, not exponentiation.
result = 2 ** 3
print(result)
Fix the augmented assignment operation:
count = 5
count =+ 2
print(count)
Hint: 💡 The order of characters in augmented assignment matters.
Issue: <b>=+</b> is not a valid operator (it's assigning positive 2, not adding).
count = 5
count += 2
print(count)
Fix the membership test:
name = "Alice"
if name in ["Bob", "Charlie", "Dave"]:
print("Found")
Hint: 💡 The code works but doesn't match the likely intention.
Issue: Testing for "Alice" in a list that doesn't contain it.
name = "Alice"
if name in ["Alice", "Bob", "Charlie"]:
print("Found")
Fix the floating-point division issue:
average = (3 + 5 + 2) / 0
print(average)
Hint: 💡 Division by zero is mathematically undefined.
Issue: Attempting to divide by zero will raise a ZeroDivisionError.
average = (3 + 5 + 2) / 3 # Using correct divisor
print(average)
Fix the chained comparison:
x = 5
if 1 < x > 10:
print("In range")
Hint: 💡 Chained comparisons must express a consistent relationship.
Issue: The condition can never be True (x cannot be both >1 and >10).
x = 5
if 1 < x < 10:
print("In range")
Fix the logical operation:
is_valid = True
is_active = False
if is_valid and is_active or:
print("Access granted")
Hint: 💡 The 'or' operator requires a second operand.
Issue: Incomplete logical expression after 'or'.
is_valid = True
is_active = False
if is_valid and is_active:
print("Access granted")
Fix the identity comparison:
x = [1, 2, 3]
y = [1, 2, 3]
if x is y:
print("Same object")
Hint: 💡 'is' checks for object identity, not equality.
Issue: Two different list objects with same values.
x = [1, 2, 3]
y = [1, 2, 3]
if x == y:
print("Equal values")
Fix the bitwise operation:
flags = 0b1010
mask = 0b1100
result = flags and mask
print(bin(result))
Hint: 💡 This is using logical AND instead of bitwise AND.
Issue: 'and' is a boolean operator, not bitwise.
flags = 0b1010
mask = 0b1100
result = flags & mask
print(bin(result))
Fix the operation to correctly calculate the average:
a, b, c = 10, 20, 30
average = a + b + c / 3
print(average)
Hint: 💡 Division has higher precedence than addition.
Issue: Only 'c' is being divided by 3 due to precedence rules.
a, b, c = 10, 20, 30
average = (a + b + c) / 3
print(average)