Iterations Debugging#

Section Title: Iterations Debugging

  • Each of the following short code contains one or more bugs.     

  • Please identify and correct these bugs.

  • Provide an explanation for your answer.

Question-1#

for i range(6):
  print(i)

Solution

in in the first line is missing.

Question-2#

for i in range(10):
print(i)

Solution

Indentation of the second line is missing.

Question-3#

while i in range(10):
  print(i)

Solution

i is undefined, or a for loop can be used instead of a while loop.

Question-4#

i = 5

while i in range(10):
  print(i)

Solution

Infinite loop: You can increase the values of i by adding 1 after the print statement using i += 1.

Question-5#

x = 3

while x > 0:
  print(5*x)
  x += 1

Solution

Infinite loop: \(x\) is continually increasing, ensuring it remains positive, and consequently, the condition of the while loop is always True. To prevent this, you can either decrease the values of \(x\) or add a break statement.

Question-6#

x = 1

for x < 5:
  print(x)
  x += 1

Solution

Instead of a for loop use a while loop.

Question-7#

x = '1s'

try:
    y = x +1
    print(y)
except:

Solution

The code of the except part is missing. You can use pass if there is nothing to execute in the except block.