简体   繁体   中英

Python: Difference between i+=1 at the beginning and at the end of loop

I am new to Python and I am learning the basics at the moment

I am now at a point where a question came up and I can't really find a answer to this.

What is the difference between:

i = 0
while i < 10:
    i += 1
    if (i % 2) != 0: continue
    print(i)
print("End of loop")

And (line 3 moved to the end of the loop)

i = 0
while i < 10:
    if (i % 2) != 0: continue
    print(i)
    i += 1
print("End of loop")

I can't really understand the problem because in PHP and JS, I always increased my number at the end of the loop because its better to read for me.

Perhaps a logic thing I need to remember in Python?

Helllo,

First of all, it all depends on when you need to increment.

In your case, the first code starts with incrementing, ie the condition starts at 1.

in second case, it will never increment, because you will check all the time condition, which always will return 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM