Lesson 1 of 0
In Progress

Lesson #10: While Loops

While Loop is used to execute a block of statements repeatedly until a given condition is satisfied.

Example

num = 1
while num < 10:
  print(num)
  num += 1

💡 Note: we should increment the num, otherwise the loop will continue forever.

In the above example, the condition for while will be True as long as the counter variable (num) is less than 10. 

The Break Statement

The break statement is used to bring the control out of the loop when some external condition is triggered even if the while loop is True.

Example

num_1 = 1
num_2 = 3
while num_1 < 10:
  print(num_1)
  if num_1 == num_2:
    break
  num_1 += 1

The Continue Statement

The continue statement is used to bring the control out of the loop only for the current iteration.

Example

num = 1
while num < 10:
  num += 1
  if num == 3:
    continue
  print(num)