Home > Net >  Why does continue print a number even when the loop has left that number?
Why does continue print a number even when the loop has left that number?

Time:05-09

Why does number 4 get printed even when the loop is on 5.

a = 1
while a < 10:
    a = a   1
    if a < 4:
        continue
    if a > 6:
        break
    print(a)

CodePudding user response:

The number 4 is being printed because it doesn't fit the condition a<4 since 4 is not less than 4.

If you want the number 4 not to be printed, you can use if a <= 4: or if a < 5:.

CodePudding user response:

Because you have used condition if a < 4: which will be used for the values which are less than 4 but not for 4. To not print 4, you should use less than or equal (<=) instead of less(<) sign.

a = 1
while a < 10:
    a = a   1
    if a <= 4:
        continue
    if a > 6:
        break
    print(a)

This above code will use continue statement till a=4 print the values 5 and 6. If you wants only 5 to be printed out then you can use if a >= 6: instead of if a > 6:.

CodePudding user response:

Cause you set conditions for numbers from (-inf,3) to (7,9) but the numbers 4, 5 and 6 that don't have any restrictions get printed.

  • Related