Python While Loop

Let’s look at while loop

  1. Notice

    A while loop checks its condition before each iteration. Update the condition’s values so the loop can finish.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
remaining = 3
while remaining > 0:
    print(remaining)
    remaining = remaining - 1
print("done")
Live state

Top-level scope

remaining→Object 4
Object 4 · int0
This step

A while loop checks its condition before each iteration. Update the condition’s values so the loop can finish.

Check, run, check again

The condition is checked before each iteration. Something must change if the loop is to finish.

Image brief

Alt text
A while loop checks its condition, runs its body if true, and returns to the condition; false leaves the loop.
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python While Loop". Teaching focus: The condition is checked before each iteration. Something must change if the loop is to finish. Depict exactly the relationships and labels in this reference diagram: CHECK CONDITION <---------+ | | +-- True --> LOOP BODY-+ | +-- False --> CONTINUE Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A while loop checks its condition, runs its body if true, and returns to the condition; false leaves the loop.

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
remaining = 3
while remaining > 0:
    print(remaining)
    remaining = remaining - 1
print("done")
Live state

Top-level scope

remaining→Object 4
Object 4 · int0
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
3
2
1
done

What do you expect this program to print?

What does this example display?

remaining = 3
while remaining > 0:
    print(remaining)
    remaining = remaining - 1
print("done")
What does this example display?
Choose one answer. You can try again.

Answer and explanation

3 2 1 done

Follow the printed values in order. The output is: 3 2 1 done

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

A while loop checks its condition before each iteration. Update the condition’s values so the loop can finish.

A while loop checks its condition before each iteration. Update the condition’s values so the loop can finish.

While Loop

The while loop in Python is a powerful control structure that lets you repeat a block of code as long as a specified condition remains True. It's commonly used when the number of iterations isn’t predetermined — making it ideal for condition-driven execution.

Basic Syntax

while condition:
    # block of code
  • while – a keyword that starts the loop.
  • condition – an expression that is evaluated before each loop iteration. If it is True, the loop continues; if False, it stops.
  • : – a colon indicates the start of the indented block.
  • The indented block of code underneath runs each time the condition is True.

Example 1: Printing from 1 to 5

The loop starts with i = 1. Each iteration prints i and increases it by 1. When i becomes 6, the condition i <= 5 fails and the loop exits.

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

Important Check: Avoid Infinite Loops

A common pitfall with while loops is forgetting to update the condition variable, which can result in an infinite loop.

# This will run forever
i = 1
while i <= 5:
    print(i)
    # missing i += 1

Tip: Always make sure the condition variable is being modified inside the loop.

Example 2: User Input Until Correct

The loop runs until the correct password is entered. Each incorrect attempt prompts the user again.

password = ""
while password != "open123":
    password = input("Enter the password: ")

print("Access granted!")
Enter the password: 123
Enter the password: pass
Enter the password: open123
Access granted!

Using break to Exit Early

You can use the break statement to exit the loop when a specific condition is met, even if the loop condition is still True.

i = 1
while True:
    print(i)
    if i == 3:
        break
    i += 1
1
2
3

Explanation: Although the loop is set to run while True, the break statement exits it when i becomes 3.

Using continue to Skip Iterations

You can use the continue statement to skip the rest of the code inside the loop for the current iteration and immediately jump to the next iteration. This is useful when you want to ignore certain values or cases without exiting the loop entirely.

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

Explanation: When i == 3, continue skips the print statement and moves to the next iteration.

What to remember

Connect what you noticed in the example with the idea below.

Remember

A while loop checks its condition before each iteration. Update the condition’s values so the loop can finish.

Watch out for this idea

A while loop always runs its body at least once.

This is the misconception to avoid.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Python Break and Continue →