PYTHON WHILE LOOP

Repeat Python statements while a condition is true, using practical loops for counters, validation, menus, transactions, retries, and real-world automation.

🔄 What is a While Loop in Python?

A while loop repeatedly executes a block of Python code as long as a specified condition remains True. It is useful when the number of repetitions is not known in advance and the loop should continue until a particular condition changes.

1. While Loop Syntax
The condition is checked before every iteration. When the condition becomes False, Python exits the loop.
Basic Syntax
while condition:
    # statements to execute

    # update the condition
Important: Make sure something inside the loop eventually changes the condition. Otherwise, the program may create an infinite loop.
2. How a While Loop Works
Start
↓
Check Condition
↓
Condition True → Execute Loop Body
↓
Update Value
↓
Check Condition Again
↓
Condition False → Exit Loop
3. Simple Example – Counting Numbers
A basic while loop can be used to process a sequence of numbers one at a time.
Counter Example
number = 1

while number <= 5:
    print(number)
    number += 1
Output: 1 2 3 4 5
4. Real-Time Example 1 – ATM PIN Validation
An ATM can allow a customer a limited number of attempts to enter the correct PIN.
ATM PIN Attempts
correct_pin = "2580"

attempts = 0
max_attempts = 3

entered_pins = ["1234", "1111", "2580"]

while attempts < max_attempts:

    entered_pin = entered_pins[attempts]

    attempts += 1

    if entered_pin == correct_pin:
        print("PIN accepted")
        print("Access granted")
        break

    else:
        print("Incorrect PIN")

if attempts == max_attempts and entered_pins[attempts - 1] != correct_pin:
    print("Card temporarily blocked")
Output: Incorrect PIN Incorrect PIN PIN accepted Access granted
Real-world use: Similar retry logic is used for authentication, verification codes, payment authorization, and account access.
5. Real-Time Example 2 – Shopping Cart Processing
A shopping system can process cart items one by one until all products have been handled.
Shopping Cart
cart = [
    ("Laptop Bag", 1500),
    ("Wireless Mouse", 800),
    ("Keyboard", 1200)
]

index = 0
total = 0

while index < len(cart):

    product = cart[index]

    print("Processing:", product[0])

    total += product[1]

    index += 1

print("Cart Total:", total)
Output: Processing: Laptop Bag Processing: Wireless Mouse Processing: Keyboard Cart Total: 3500
6. Real-Time Example 3 – Bank Account Balance
A banking application can process a series of withdrawals while sufficient balance is available.
Bank Withdrawal
balance = 20000

withdrawals = [3000, 5000, 4000, 6000]

index = 0

while index < len(withdrawals):

    amount = withdrawals[index]

    if amount <= balance:

        balance -= amount

        print("Withdrawal:", amount)
        print("Balance:", balance)

    else:

        print("Insufficient balance")
        break

    index += 1
Output: Withdrawal: 3000 Balance: 17000 Withdrawal: 5000 Balance: 12000 Withdrawal: 4000 Balance: 8000 Withdrawal: 6000 Balance: 2000
7. Real-Time Example 4 – Online Order Status
An order tracking system can repeatedly check the current status until the package is delivered.
Order Tracking
statuses = [
    "Order Placed",
    "Packed",
    "Shipped",
    "Out for Delivery",
    "Delivered"
]

index = 0

while index < len(statuses):

    status = statuses[index]

    print("Current Status:", status)

    if status == "Delivered":
        print("Order completed")
        break

    index += 1
Output: Current Status: Order Placed Current Status: Packed Current Status: Shipped Current Status: Out for Delivery Current Status: Delivered Order completed
8. Real-Time Example 5 – Employee Attendance
An HR application can process employee attendance records one by one.
Attendance Processing
employees = [
    ("Rahul", "Present"),
    ("Priya", "Absent"),
    ("Amit", "Present"),
    ("Neha", "Present")
]

index = 0
present_count = 0

while index < len(employees):

    employee = employees[index]

    print(employee[0], "-", employee[1])

    if employee[1] == "Present":
        present_count += 1

    index += 1

print("Employees Present:", present_count)
Output: Rahul - Present Priya - Absent Amit - Present Neha - Present Employees Present: 3
9. Real-Time Example 6 – Customer Service Queue
A customer support system can process customers from a queue until no customers remain.
Support Queue
customers = [
    "Customer A",
    "Customer B",
    "Customer C"
]

while customers:

    customer = customers.pop(0)

    print("Serving:", customer)

print("All customers served")
Output: Serving: Customer A Serving: Customer B Serving: Customer C All customers served
10. Real-Time Example 7 – Password Retry System
A system can allow a limited number of password attempts before stopping authentication.
Password Attempts
correct_password = "python123"

passwords = [
    "hello123",
    "python",
    "python123"
]

attempt = 0
max_attempts = 3

while attempt < max_attempts:

    password = passwords[attempt]

    print("Checking password...")

    if password == correct_password:
        print("Login successful")
        break

    print("Incorrect password")

    attempt += 1

else:
    print("Account locked")
Output: Checking password... Incorrect password Checking password... Incorrect password Checking password... Login successful
11. Real-Time Example 8 – Inventory Stock Processing
An inventory system can repeatedly process sales while stock is available.
Inventory Management
stock = 5

orders = [1, 2, 1, 1, 2]

index = 0

while index < len(orders):

    quantity = orders[index]

    if quantity <= stock:

        stock -= quantity

        print("Order processed:", quantity)
        print("Remaining stock:", stock)

    else:

        print("Order cannot be fulfilled")
        break

    index += 1
Output: Order processed: 1 Remaining stock: 4 Order processed: 2 Remaining stock: 2 Order processed: 1 Remaining stock: 1 Order processed: 1 Remaining stock: 0 Order cannot be fulfilled
12. Real-Time Example 9 – Data Validation
While loops are useful when an application needs to repeatedly validate input until valid data is available.
Input Validation
ages = [15, 12, 17, 25]

index = 0

while index < len(ages):

    age = ages[index]

    if age >= 18:
        print("Valid age:", age)
        break

    print("Age", age, "is below 18")

    index += 1

if index == len(ages):
    print("No valid age found")
Output: Age 15 is below 18 Age 12 is below 18 Age 17 is below 18 Valid age: 25
13. Real-Time Example 10 – Restaurant Order Processing
A restaurant application can process pending orders one by one until the order queue becomes empty.
Restaurant Orders
orders = [
    "Order #101",
    "Order #102",
    "Order #103",
    "Order #104"
]

while len(orders) > 0:

    current_order = orders.pop(0)

    print("Preparing", current_order)

print("All orders completed")
Output: Preparing Order #101 Preparing Order #102 Preparing Order #103 Preparing Order #104 All orders completed
14. While Loop with Break
The break statement immediately stops a while loop when a required condition occurs.
Break Example
number = 1

while number <= 10:

    if number == 6:
        break

    print(number)

    number += 1
Output: 1 2 3 4 5
15. While Loop with Continue
The continue statement skips the current iteration and moves to the next iteration.
Continue Example
number = 0

while number < 5:

    number += 1

    if number == 3:
        continue

    print(number)
Output: 1 2 4 5
16. While Loop with Else
The else block of a while loop executes when the loop finishes normally without being stopped by a break statement.
While Else
number = 1

while number <= 3:

    print("Processing:", number)

    number += 1

else:

    print("Processing completed")
Output: Processing: 1 Processing: 2 Processing: 3 Processing completed
17. Common While Loop Mistakes

Forgetting to Update the Variable

Avoid Infinite Loop
# Incorrect

number = 1

while number <= 5:
    print(number)

# number never changes

Correct Version

Correct
number = 1

while number <= 5:

    print(number)

    number += 1
Important: Always verify that the loop condition will eventually become False, unless you intentionally need a loop that runs continuously.
18. While Loop vs For Loop

While Loop

Best when the number of repetitions depends on a condition and is not necessarily known beforehand.

while
balance = 1000

while balance > 0:

    print("Balance:", balance)

    balance -= 250

For Loop

Best when you want to iterate through a known sequence or a known range of values.

for
for number in range(1, 5):

    print(number)
19. Best Practices for While Loops

1. Keep the Condition Clear

Use a condition that clearly explains when the loop should continue.

2. Update the Loop Variable

Make sure the loop moves toward its stopping condition.

3. Use Break Carefully

Use break when a meaningful event requires the loop to stop early.

4. Avoid Unnecessary Infinite Loops

A loop should normally have a predictable termination condition.

Key Takeaways

  • A while loop repeatedly executes code while its condition is True.
  • The condition is checked before every iteration.
  • Always make sure the loop can eventually terminate unless an infinite loop is intentionally required.
  • break immediately exits the loop.
  • continue skips the current iteration.
  • A while loop can also have an else block.
  • While loops are useful for validation, retries, queues, transactions, monitoring, and repeated processing.
  • Real-world applications include ATM systems, shopping carts, banking, inventory, order tracking, employee systems, and customer support.