0
0
PythonHow-ToBeginner · 3 min read

How to Use While Loop in Python: Syntax and Examples

In Python, a while loop repeatedly runs a block of code as long as a given condition is true. It starts by checking the condition, and if true, executes the code inside the loop until the condition becomes false.
📐

Syntax

The while loop syntax includes the keyword while, a condition to check, and a block of code indented underneath that runs repeatedly while the condition is true.

  • while: starts the loop
  • condition: a test that must be true to continue looping
  • code block: the indented statements that run each time the condition is true
python
while condition:
    # code block to repeat
💻

Example

This example counts from 1 to 5 by printing numbers and increasing the count each time until the condition becomes false.

python
count = 1
while count <= 5:
    print(count)
    count += 1
Output
1 2 3 4 5
⚠️

Common Pitfalls

One common mistake is forgetting to update the condition inside the loop, which causes an infinite loop that never stops. Another is using a condition that is always false, so the loop never runs.

python
count = 1
# Wrong: missing update causes infinite loop
while count <= 5:
    print(count)
    # count += 1  # This line is missing

# Correct way:
count = 1
while count <= 5:
    print(count)
    count += 1
Output
1 2 3 4 5
📊

Quick Reference

Remember these tips when using while loops:

  • Always ensure the loop condition will eventually become false.
  • Use break to exit a loop early if needed.
  • Indent the code inside the loop properly.
  • Use continue to skip to the next loop iteration.

Key Takeaways

A while loop runs code repeatedly while its condition is true.
Always update variables inside the loop to avoid infinite loops.
Indentation is required to define the loop's code block.
Use break and continue to control loop flow when needed.
Test your loop conditions carefully to ensure proper execution.