简体   繁体   中英

Loop start from 2 instead of 1 in python continue statement

I am learning continue statement in python while loop. If I run a following code, the output shows from 2 instead of 1.

    a = 1
    while a <= 8:
        a += 1
        if a == 5:
            continue
        print(a)

You go through the body of the while condition once, 1 + 1 = 2 then print(2)

a += 1 is coming before the print statement, that's why it's printing 2. Your a == 5 condition is also not executing because a is 2.

you can elaborate your question more if you haven't got the answer yet.

Your current code is below and I have annotated it with the value of a

a = 1 #### a is 1 here obviously ####
while a <= 8:
    a += 1 #### a is incremented by 1, so the value of a is 2 here ####
    if a == 5:
        continue
    print(a) #### the value of a is 2 when you print ####

To have the counter start from 1 instead:

a = 1 #### a is 1 here obviously ####
while a <= 8:
    # remove this step that increments a #### value of a is still 1
    if a == 5:
        continue
    print(a) #### the value of a is 1 when you print ####
    a += 1 # increment a here instead

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