Sharpen your Python debugging skills with ‘Find & Fix’ exercises for variable mistakes—naming errors, assignment issues, scope bugs—perfect for hands-on learning!.
Topic: variables
Fix the invalid variable name:
global-var = 10
print(global-var)
Hint: 💡 Python variable names cannot contain hyphens.
Issue: Hyphens are interpreted as subtraction operators.
global_var = 10
print(global_var)
Fix the variable assignment error:
print(message)
message = "Hello"
Hint: 💡 Variables must be defined before use.
Issue: Trying to access `message` before assignment.
message = "Hello"
print(message)
Fix the None comparison:
result = None
if result == None: # Works but non-idiomatic
print("Empty")
Hint: 💡 Python has a dedicated operator for `None` checks.
Issue: Should use identity comparison (`is`) for `None`.
result = None
if result is None:
print("Empty")
Fix the type confusion bug:
price = "10"
total = price * 2
print(total) # Outputs "1010" (unexpected)
Hint: 💡 Strings and numbers behave differently with `*`.
Issue: Dynamic typing allows the operation but produces undesired string concatenation.
price = 10 # or int("10")
total = price * 2
print(total) # Outputs 20
Fix the None-related crash:
def get_user():
return None
user = get_user()
print(user.upper()) # AttributeError
Hint: 💡 Methods can't be called on `None`.
Issue: Attempting to call `.upper()` on a `None` value.
def get_user():
return None
user = get_user()
if user is not None:
print(user.upper())
else:
print("No user found")
Fix the dynamic typing pitfall:
def add(a, b):
return a + b
print(add(5, 3)) # 8
print(add("5", "3")) # "53" (unexpected for numbers)
Hint: 💡 The `+` operator has different behaviors per type.
Issue: Function works differently with strings vs numbers.
def add(a, b):
return int(a) + int(b)