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 – if în while loop

I am studiing the Python Fundamentals and i have some trouble understanding this folowing example:

c = 1 

while c < 5:
    c = c + 1

    if c >= 4:

        print("string")

        print(c)

   else:

        continue

And the output is:

string

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

4

string

5

Could someone explain to me please, why i have this output?

>Solution :

Consider the third iteration when c is 3.

c = c + 1 increments the value to 4, and goes into the if statement and prints out the values.

Now c is equal to 4. On the next iteration, c < 5 (because its value is 4) and loops again. It gets incremented again and goes into the if statement again.

Therefore, it prints out 2 more values, hence why you see your output.

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