Skip to Main Content

Python Basics

While Loops

 while  loops

 while  loops execute a set of statements as long as a condition is true.

Importing Modules

while  loops execute a set of statements as long as a condition is true.

Syntax

i = 1
while i < 5:
  print(i)


This will print the data '1' without stopping as long as  i  is less than 5. Run the codes below.



We can stop this by adding a line of code to increase the value of   i  with each iteration. 
 

i = 1
while i < 6:
  print(i)
i += 1

 

With the  break  statement we can stop the loop even if the  while  condition is true.

Syntax

i = 1
while i < 5:
  print(i)
  if i == 2:
    break
  i += 1


Example

while  loops with  continue 

With the  continue  statement, we can skip over a part of the loop where an additional condition is set, and then go on to complete the rest of the loop. 

Syntax

i = 0
while i < 5:
  i += 1
  if i == 2:
    continue
  print(i)

Example

 while  loops with  else 

With the else statement, we can run a block of code once when the condition no longer is true.

Syntax

i = 1
while i < 5:
  print(i)
  i += 1
else:
    print("i is no longer less than 5")


Example

Video Guide

Exercises

Assign the integer 10 to variable i and increase it by 10 for each iteration. 

1.  while  loop - Print the iteration as long as it is below 100. 

2.  while  loops with  continue  - Skip the iteration when it is at 50. 

3.  while  loops with  break  - Stop the iteration at 70. 

4.  while  loops with  else  - Once the iteration reaches 100, print "i is no longer less than 100".