Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python while loop, print sequential odd numbers

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading