While loop in Python

The while loop in Python is used when you want an operation to be repeated as long as a specified condition is met.

What is a While loop in Python?

The While loop is used to iterate (repeat) part of the program several times. If the number of iterations (repetitions) you want to perform is not fixed, it is recommended to use a While loop. Generally, we can imagine the While loop as a repetition of one or more sequences that occur as long as one or more conditions are met.

 

The image to the right (same as the introduction, press for larger) shows the flow chart for how the while loop works.

 

  • The loop is executed as long as the condition is true
while loop in Java

Create a While loop in Python

 

while condition:
    should happen within the loop

All code indented after the while command will execute if the condition is True

EXAMPLE:  HOW TO CREATE A WHILE LOOP

We’ll see a simple example of how we can use the while loop to perform an operation while the specified condition is met.

  • We will start by declaring an integer variable (named ” i “) and assign the value zero.

 

After that we create our while loop.

  • The condition we want to use is that, when the variable ” i ”  is less than 5.
  • The operation within the loops prints the value for the variable i for every operation.
  • After the operation is performed, the variable  i  is incremented by 1.

 

i = 0 

while i < 5: 
   print(i) 
   i = i +1 # add 1 to the variable i

 

In this example, we print the value for the variable i as long as the condition is met. In other word,  as long as i is less than 5. The program will thus print the value five times and then end the while loop. The result is

 

0
1
2
3
4

Note, what had happened if i ++ had not been in the loop? Exactly, the condition for the loop will always be fulfilled (zero is always less than five) and the while loop will not end.