Home > OS >  Continue while loop in Python
Continue while loop in Python

Time:12-11

Below is my code for continue while loop. I'm getting the correct o/p after passing the continue statement.

#!/usr/bin/python
# -*- coding: utf-8 -*-
i = 0
while i <= 6:
    i  = 1
    if i == 3:
        continue
    print i

O/p:

1
2
4
5
6
7

my confusion is while i<=6, so o/p should be 1,2,4,5,6. how its going for the next interation, 7 is greater than 6 ?

CodePudding user response:

The condition is only checked at the start of each iteration.

It checks 6 <= 6, which is True, then increments i to 7, then checks if 7 == 3, which is False, then prints 7

CodePudding user response:

This has nothing to do with continue. You are printing after i =1. So, if iteration starting when i=6 is the last one, then in that same iteration, i becomes i=7 after i =1, and is printed as is

i=0
while i<=6:
   i =1
   print(i)

also displays 1 to 7.

CodePudding user response:

You have incremented 'i' before executing the other operations in the loop. Therefore when i=6 you enter the loop for the last time, increase it by one, and then print 7

  • Related