While Loops

3 min read ·

A while loop is used to execute a block of code repeatedly as long as a given condition is True.
Python keeps checking the condition:
  • If condition is True → loop runs
  • If condition becomes False → loop stops

Why Use a while Loop?

Use a while loop when:
  • You do not know in advance how many times the loop should run
  • The loop depends on a condition
  • Repetition is required until a condition changes

Basic Idea of while Loop

  • while is a keyword
  • Condition must return True or False
  • Indentation defines the loop body
Note

If the condition never becomes False, the loop will run forever.


Simple Example of while Loop

  • Loop starts with i = 1
  • Condition: i <= 5
  • Value of i changes every iteration

Flow of while Loop Execution

  1. Condition is checked
  2. If condition is True → code runs
  3. Variable is updated
  4. Condition is checked again
This continues until the condition becomes False.

while Loop with Condition


while Loop with Boolean Condition


while Loop with User Input


Infinite while Loop

Caution

Always make sure the condition can become False.


Common Mistake in while Loop

Missing Update Statement ❌

This creates an infinite loop.
Stop

Forgetting to update the loop variable is the most common while loop error.


Real World Example

Real World Scenario

ATM keeps running until the user exits


Exercise

Practice Task
  1. Print numbers from 1 to 10 using while loop
  2. Print numbers in reverse order
  3. Create a loop that runs until user enters 0
  4. Observe what happens if condition never changes