Rewrite the following program using for loop.
lst = ['desert', 'dessert', 'to', 'too', 'lose', 'loose']
s = 'Mumbai'
i = 0
while i < len(lst) :
if i > 3 :
break
else :
print(i, lst[i], s[i])
i += 1
Here's the equivalent program using a for loop:
lst = ['desert', 'dessert', 'to', 'too', 'lose', 'loose']
s = 'Mumbai'
for i in range(len(lst)):
if i > 3:
break
else:
print(i, lst[i], s[i])
In this version, the for loop iterates over the indices of the lst list using range(len(lst)). The if condition inside the loop checks whether i is greater than 3, and if so, it breaks out of the loop. Otherwise, it prints the values of i, lst[i], and s[i]. The loop increment is handled automatically by the for loop construct, eliminating the need for an explicit increment (i += 1).
0 Comments:
Post a Comment