top of page

Python While Loop

Python while loop is also a looping statement and its is used to run the loop.

In while loop, you have to initialize the value and increment it.

we have to give the condition after while keyword to decide when will while loop is going to break.

Print 1 to 7 

i = 1

while i < 8:

    print(i)

    i = i + 1 

Break Keyword

Break keyword is use to break the while loop.

Break at 5

i = 0

while i<9:

    print(i)

    if i == 5:

        break

Continue Keyword

While loop runs in a loop from the start of the block and goes till end. But when the loop encounter continue keyword instead of going till the end of the loop. the code will continue from the continue keyword and goes up again. 

print 1 to 9 and skip the 7

i = 1

while i < 10:

    if i == 5:

        continue

    print(i)

    i = i + 1

while Else 

Like If else we do have for else and the else part of the while loop runs once the iteration gets completed.

While Else

i = 1

while i < 8:

    print(i)

    i = i + 1

else:

    print("loop is completed") 

Key Point to Remember:

  • If while loop get break with the break keyword and didn't complete its execution then else part will not run.

  • Else part will only run when the execution of while loop is completed.

While Else

i = 0

while i<9:

    print(i)

    if i == 5:

        break

    i = i + 1

else:

    print("loop is completed")

bottom of page