Python While Loop

A While loop statement execute the target statement again and again in a loop until the given condition is true.

Syntax
while expression:
statement(s)

Statement can be a single statement or a block of statements. The loop iterates and when the condition becomes false, control of the program passes to the
line immediately following the loop

Indentation in python used as a method for grouping the set of statements.

flow chart of While Loops

Example of While Loop :

count = 0
                         #Count Starter
while count < 10:
                 #while condition
   print('The count is:', count)
   count = count + 1
              #increase the counter

Output :

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
The count is: 9

While loop with else Statement :

count = 0
while count < 10:
   print('The count is:', count)
   count = count + 1
else:
    print ("End Of Loop")

Output :

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
The count is: 9
End Of Loop

While Loop in one line :
If While loop consist of one statement, it can be written in one line.

If you run this program, it will go in infinite Loop, you can cancel it by pressing the stop button in Jupyter notebook. In Idle press Ctl+C to stop.

Status= True
while (True): print 'Go to infinite loop'
print "This is infinite Loop!"

How to stop infinite loop in Jupyter Notebook
Press the Stop button.

1 thought on “Python While Loop”

Leave a Comment