3. Convert the following for loop to while loop
p=0
for k in range (5,19,3):
print("k=",k)
p+=k
else:
print(k*2)
print(p)
Output
k= 5
k= 8
k= 11
k= 14
k= 17
34
55
My while loop
def q3():
k=5
p=0
while p<=55:
print("k=",k)
k+=3
p+=k
else:
print(k*2)
print(p)
Output
k= 5
k= 8
k= 11
k= 14
k= 17
40
70
Question.
In the last two lines of the for-loop my output for k x 2 was 34 (last k value generated=17 x 2) print(p) was 55 (sum of all k values generated)
Whereas the last two lines of my while-loop produced k x 2: 40 (Why is it generating 40?) print(p) was 70 (Again, why is it producing 70?)
k+=3
is executed finally in the while-loop even if it is exited before the next iteration. Nothing similar happens in the for-loop.