Python While Loop

In this tutorial you will learn:

  • While loop in Python
  • Nested while  loop in Python
  • Break statement in while  loop
  • Continue statement in while loop

While loop in Python

A while loop in Python is just like any in any other programming language. Just like a for loop a while loop also needs initialization, condition and increment. A while loop keeps on running until the condition is true. If we want the loop to run indefinitely then we can pass 1 or true in while loop. Let’s go through the examples we did in for loop using while loop.

Example:

  1. numbers = [67,85,23,45,6,7,8,2,1]
  2.  
  3. index = 0
  4. print("\n\nWHILE Loop Example")
  5. print("This list contains the following: ")
  6. while index<len(numbers):
  7. print(numbers[index], end=" ")
  8. index+=1

Nested while loop in Python

Loops can be nested at many levels but there is one big disadvantage and that is it increases the computation time of your code by using up most the resources of the hardware in case of large datasets or while executing a complex block of code many number of times. But in some cases they are quite useful such as for printing list of lists.

Example:

  1. sum = 0
  2. index = 0
  3. print("\n\nSum of numbers: ")
  4. while index<len(numbers):
  5. sum+=numbers[index]
  6. index+=1
  7. print(sum, end=" ")

Break statement in while loop

Break statement is used to stop the execution of a block of code and it does its job in while loop as well.

Example:

  1. myLists = [["Testing", 1, "Python"], ["John", "Mike", "Todd"]]
  2.  
  3. print("\n\nPrinting elements in list of lists")
  4. index = 0
  5. listItemIndex = 0
  6. while index < len(myLists):
  7. while listItemIndex < len(myLists[index]):
  8. print(myLists[index][listItemIndex], end=" ")
  9. listItemIndex+=1
  10. index+=1

Continue statement in while loop

This statement is used to skip a loop iteration and its usage is similar to that of for loop.

Example:

  1. index = 0
  2. print("\n\nStop the loop if 8 is found in numbers: ")
  3. while index<len(numbers):
  4. if numbers[index]==8:
  5. break
  6. print(numbers[index], end=" ")
  7. index+=1

Add new comment