Python while Loop

If you want to execute a block of code over and over again you should use while loop. The block of while statement will be executed as long as the condition is true. In Python the while statement includes the following:

  • The while keyword
  • The condition part
  • A colon(:)
  • An indented block at the starting of next line

Example:

  1. i = 1
  2. while i < 10:
  3. print(i)
  4. i=i+1

Output:

1
2
3
4
5
6
7
8
9

break Statement

You can break a loop early using break statement. If the execution reaches a break statement its immediately breaks the loop and exits from the block of the while loop. A break statement just contains the break keyword.

Example:

  1. i = 1
  2. while i < 10:
  3. print(i)
  4. if i == 5:
  5. break
  6. i=i+1

Output:

1
2
3
4
5

continue Statement

You can stop a current iteration and continue with the next using the continue statement. If the execution reaches the continue statement its immediately stop the current iteration and continue with the next iteration. A continue statement just contains the continue keyword.

Example:

  1. i = 0
  2. while i < 10:
  3. i=i+1
  4. if i == 5:
  5. continue
  6. print(i)

Output:

1
2
3
4
6
7
8
9
10