Skip to main content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Python for Basic Data Analysis: 1.16 While loops

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of basic data manipulation and analysis.

While loops

 while  loops

 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

 

 while  loops with  breaks 

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

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".