Skip to main content

Python Loops

Python gives you two basic kinds of loop:

  • while loops
  • for loops

The while Loop

A while loop keeps running its statements for as long as its condition stays true.

Note: Don't forget to increase i. If you leave that out, the loop never ends.

Any variables the while loop depends on must exist before it starts. Here that means an indexing variable, i, with a starting value of 1.

Example

Keep printing i while it is below 6:

Prompt
Write a Python program that uses a while loop to print numbers 1 through 5. Initialize i to 1 and increment it each iteration.
Output: complete Python program

The break Statement

A break statement ends the loop right away, even though the while condition is still true:

Example

Leave the loop as soon as i is 3:

Prompt
Write a Python program that uses a while loop with a break statement. Print i and break when i equals 3.
Output: complete Python program

The continue Statement

A continue statement abandons the current iteration and moves on to the next one:

Example

Skip printing when i is 3 and move on:

Prompt
Write a Python program that uses a while loop with a continue statement. Skip printing when i equals 3.
Output: complete Python program

The else Statement

An else statement gives the loop a block of code that runs one time, at the moment the condition stops being true.

Note: A loop that ends through a break statement does NOT run its else block.

Example

Print a message when the condition turns false:

Prompt
Write a Python program that uses a while loop with an else block. Print numbers 1-5, then print a message when the loop condition is false.
Output: complete Python program