I’d appreciate some clarification on my python code.
The goal was to create a while loop in order to print every third sequential odd number between 2 and 19, inclusive. (The expected output is 7, 13, 19.)
After some trial and error, I got the following code to work.
i = 2
count = 0
while i <= 19:
if (i%2 != 0):
count += 1
if count == 3:
print(i)
count = 0
i += 1
However, this is what I incorrectly expected to work:
i = 2
count = 0
while i <= 19:
if (i%2 != 0):
count += 1
if count == 3:
print(i)
i += 1
Why is line 9 (count = 0) needed in order for this to run properly? Why isn’t line 2 enough?
>Solution :
Try walking through the code and tracking what the variables i
and count
are at each iteration of the loop.
For example your first snippet will produce:
i=2, count=0 # init
i=3, count=1
i=4, count=1
i=5, count=2
i=6, count=2
i=7, count=3 # 7 is printed, count is reset to 0
i=8, count=0
i=9, count=1
...
While the second will produce:
i=2, count=0 # init
i=3, count=1
i=4, count=1
i=5, count=2
i=6, count=2
i=7, count=3 # 7 is printed, count is not reset
i=8, count=3
i=9, count=4
...
Notice in the second example that the count is always greater than or equal to 3 after printing the first value because it’s never reduced or set back to 0. You could modify that line to if count % 3 == 0
and not reset the count to 0 after printing as well.