Control Flow - While Loops

The while statement iterates (repeats) the same code block as long as certain condition is met. Iteration means executing the same block of code over and over. A code that implements iteration is called a loop. Python has two primitive loop commands:

while loops Indefinite iteration The number of times the loop is executed isn’t specified explicitly in advance
for loops Definite iteration The number of times the designated block will be executed is specified explicitly at the time the loop starts

Before every iteration the while condition is calculated. If True - the block beneath the command is executed.

Here is an example:

#while x = 1 while x < 5: print(x) x += 1 print("loop ended")

Here is a diagram describing the process:

Responsive image

The continue Statement

Using the continue statement we can skip the current iteration, and continue to the next one:

#continue x = 0 while x < 5: x += 1 if x == 3: continue print(x)

The break Statement

Using the break statement we can exit the loop (not just one iteration):

#break x = 1 while x < 5: if x == 3: break print(x) x += 1

The else Statement

Using the else statement we can run code when the condition is False:

#else x = 1 while x < 5: print(x) x += 1 else: print('While loop is a great tool')

Nested while Statements

It is possible to use a nested while statement:

#nested while x = 1 while x < 10: print(x) while x < 3: print("We are at the very beginning") x += 1 else: print('While loop is a great tool')

Exercise

  1. Define a variable with the value of 2.
  2. Create a while loop that runs as long value equals less than 20.
  3. Inside the loop print the variable and add 2 to the variable.

#Write your code here: