🔄 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.
while condition:
# statements to execute
# update the condition
number = 1
while number <= 5:
print(number)
number += 1
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")
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)
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
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
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)
customers = [
"Customer A",
"Customer B",
"Customer C"
]
while customers:
customer = customers.pop(0)
print("Serving:", customer)
print("All customers served")
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")
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
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")
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")
number = 1
while number <= 10:
if number == 6:
break
print(number)
number += 1
number = 0
while number < 5:
number += 1
if number == 3:
continue
print(number)
number = 1
while number <= 3:
print("Processing:", number)
number += 1
else:
print("Processing completed")
Forgetting to Update the Variable
# Incorrect
number = 1
while number <= 5:
print(number)
# number never changes
Correct Version
number = 1
while number <= 5:
print(number)
number += 1
While Loop
Best when the number of repetitions depends on a condition and is not necessarily known beforehand.
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 number in range(1, 5):
print(number)
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.