Python while Loop

A while loop is used to execute a block of code repeatedly until some conditions are true.

Example

To prevent from running the loop forever, increament the value of i after every loop.


i = 1
while i < 5:
    print(i)
    i += 1
  
Output
1
2
3
4

The break statement

The break statement is used to terminate the loop before the looping through all items is complete.

Example

Terminate the loop when i is mango:


fruits = ["grapes", "mango", "apple", "pineapple", "banana"]
i = 0
while i < len(fruits):
    #go to next loop if the current value of i is apple
    if(fruits[i] == "apple"):
        break
    print(fruits[i])
    i += 1
print("End of program")
  
Output
grapes
mango
End of program

The continue statement

The continue statement is used to skip the current loop and continue with the next loop.

Example

Continue when i is "apple"


fruits = ["grapes", "mango", "apple", "pineapple", "banana"]
x = 1
i = 0
while x < len(fruits):
    x += 1
    if(fruits[i] == "apple"):
        continue
    print(fruits[i])
    i += 1
print("End of program")
  
Output
grapes
mango
End of program