Could you explain why the output of this program is equal to 6? I’m confused on how it’s 6
k = 0
total = 0
while (k < 4):
total += k
k += 1
print(“ The total is”, total)
Could you explain why the output of this program is equal to 6? I’m confused on how it’s 6
k = 0
total = 0
while (k < 4):
total += k
k += 1
print(“ The total is”, total)
This program is short enough to walk through the entire thing:
First iteration: k = 0, total += 0, k += 1. Total = 0, k = 1
Second iteration: k = 1, total += 1, k += 1. Total = 1, k = 2
Third iteration: k = 2, total += 2, k += 1. Total = 3, k = 3
Fourth iteration: k = 3, total += 3, k += 1. Total = 6, k = 4
Fifth iteration does not happen because k < 4
or 4 < 4
evaluates to false.