Improve your Python debugging skills by finding and fixing common errors in for loop code. Practice loop logic, syntax, and indentation with real-world examples.
Topic: loops-for
Fix the syntax error in this for loop.
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits
print(fruit)
Hint: 💡 Check the punctuation at the end of the for statement.
Issue: Missing colon at the end of the for statement.
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Fix the infinite loop in this code.
numbers = [1, 2, 3]
for i in range(len(numbers)):
print(numbers[i])
i += 2
Hint: 💡 The loop variable in a for loop is automatically updated.
Issue: Manually modifying the loop variable (i) doesn't affect the iteration.
numbers = [1, 2, 3]
for i in range(len(numbers)):
print(numbers[i])
Fix the NameError in this nested loop.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
total += element
print(total)
Hint: 💡 Variables need to be initialized before use.
Issue: total variable is used but never initialized.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
total = 0
for row in matrix:
for element in row:
total += element
print(total)
Fix the off-by-one error in this range-based loop.
for i in range(1, 10, 2):
print(i)
# Expected to print numbers 1 through 10
Hint: 💡 Check the stop parameter of the range function.
Issue: range(1, 10, 2) stops at 9, not 10.
for i in range(1, 11, 2):
print(i)
Fix the unintended behavior in this loop that modifies a list while iterating.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num)
print(numbers)
Hint: 💡 Modifying a list while iterating over it can cause unexpected behavior.
Issue: Modifying a list during iteration can skip elements.
numbers = [1, 2, 3, 4, 5]
numbers_copy = numbers.copy()
for num in numbers_copy:
if num % 2 == 0:
numbers.remove(num)
print(numbers)
# Better alternative:
# numbers = [num for num in numbers if num % 2 != 0]
# print(numbers)
Tutorials, Roadmaps, Bootcamps & Visualization Projects