while loop

The for loop is not the only way to repeat a piece of code. Python also supports another type of loop called while loop. A for loop is made to repeat the code a specific number of times, but a while loop will keep executing the code as long as a certain condition is True.

while loop syntax:

while <some condition that is True>:
    loop body
    ...
    (back to the beginning of the loop body)

(break out of the loop if the condition is False)

while loop header begins with keyword while, followed by a condition which is a Boolean expression that returns True or False. The line ends with a colon : . The loop body is indented the same way as in a for loop. Check the example below:

i = 0
while i < 5:                
    print ( 'i: ', i )      
    i += 1               

print ('Exiting the while loop')

Run and see the console result:

i: 0              
i: 1
i: 2
i: 3
i: 4
Exiting the while loop

Here are the logic steps the computer follows when executing a while loop:

  1. Check the condition, i < 5, and evaluate whether it is true or not. If it's false, exit the loop

  2. If the condition is true, execute the code in the block.

  3. After reading all the code in the loop body, go back to the beginning of the loop and repeat from step 1.

results matching ""

    No results matching ""