#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read

Control Flow - While Loops

Learn to repeat code as long as a condition is true

What You'll Learn

  • What while loops are
  • When to use while vs for
  • Avoiding infinite loops
  • Using break and continue

What is a While Loop?

A while loop repeats code as long as something is True.

Format:

code.py
while condition:
    # do this

Example:

code.py
count = 0

while count < 5:
    print(count)
    count += 1

Output:

0 1 2 3 4

While vs For Loops

Use for when: You know how many times to repeat

code.py
# Print 5 times
for i in range(5):
    print("Hello")

Use while when: You don't know how many times

code.py
# Keep asking until correct
password = ""

while password != "secret":
    password = input("Enter password: ")

Simple Examples

Example 1: Countdown

code.py
count = 5

while count > 0:
    print(count)
    count -= 1

print("Blast off!")

Output:

5 4 3 2 1 Blast off!

Example 2: Sum until limit

code.py
total = 0
number = 1

while total < 20:
    total += number
    print(f"Added {number}, total is {total}")
    number += 1

Example 3: User menu

code.py
choice = ""

while choice != "quit":
    print("1. Start")
    print("2. Help")
    print("Type 'quit' to exit")
    choice = input("Choose: ")

Infinite Loops (Dangerous!)

Loop that never stops:

code.py
# Don't run this!
while True:
    print("Forever!")

This runs forever! Press Ctrl+C to stop.

How to avoid: Always change the condition:

code.py
# Good - stops eventually
count = 0
while count < 5:
    print(count)
    count += 1  # Changes condition!

Using break

Stop the loop early:

code.py
count = 0

while True:
    print(count)
    count += 1
    if count >= 5:
        break  # Stop here

Example: Find number

code.py
numbers = [3, 7, 2, 9, 5]
index = 0

while index < len(numbers):
    if numbers[index] == 9:
        print("Found 9!")
        break
    index += 1

Using continue

Skip to next iteration:

code.py
count = 0

while count < 5:
    count += 1
    if count == 3:
        continue  # Skip 3
    print(count)
# Shows: 1, 2, 4, 5

Practice Examples

Example 1: Guess the number

code.py
secret = 7
guess = 0

while guess != secret:
    guess = int(input("Guess (1-10): "))

    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")
    else:
        print("Correct!")

Example 2: Build total

code.py
total = 0
number = 1

while number <= 10:
    total += number
    number += 1

print(f"Sum of 1-10: {total}")
# Shows: Sum of 1-10: 55

Example 3: Login attempts

code.py
correct_password = "1234"
attempts = 0
max_attempts = 3

while attempts < max_attempts:
    password = input("Enter password: ")

    if password == correct_password:
        print("Login successful!")
        break
    else:
        attempts += 1
        remaining = max_attempts - attempts
        print(f"Wrong! {remaining} attempts left")

if attempts == max_attempts:
    print("Account locked!")

While with Lists

Process items one by one:

code.py
items = ["apple", "banana", "orange"]
index = 0

while index < len(items):
    print(items[index])
    index += 1

Remove items:

code.py
numbers = [1, 2, 3, 4, 5]

while numbers:  # While list is not empty
    num = numbers.pop()  # Remove last item
    print(f"Removed: {num}")

Real-World Examples

Example 1: ATM withdrawal

code.py
balance = 1000

while True:
    print("Balance: $" + str(balance))
    amount = int(input("Withdraw (0 to quit): "))

    if amount == 0:
        break

    if amount > balance:
        print("Insufficient funds!")
    else:
        balance -= amount
        print("Withdrew $" + str(amount))

print("Thank you!")

Example 2: Input validation

code.py
age = -1

while age < 0 or age > 120:
    age = int(input("Enter age (0-120): "))
    if age < 0 or age > 120:
        print("Invalid age!")

print(f"Your age is {age}")

Example 3: Shopping cart

code.py
cart = []

while True:
    item = input("Add item (or 'done'): ")

    if item == "done":
        break

    cart.append(item)
    print(f"Added {item}")

print("Your cart:")
for item in cart:
    print(f"- {item}")

Common Mistakes

Mistake 1: Forgetting to change condition

code.py
# Wrong - infinite loop!
count = 0
while count < 5:
    print(count)
    # Forgot: count += 1

# Correct
count = 0
while count < 5:
    print(count)
    count += 1

Mistake 2: Wrong condition

code.py
# This never runs
count = 10
while count < 5:
    print(count)

# count is already 10!

Mistake 3: Forgetting break

code.py
# Infinite loop
while True:
    print("Hello")
    # Need break somewhere!

When to Stop Loops

By count:

code.py
count = 0
while count < 10:
    # ...
    count += 1

By condition:

code.py
found = False
while not found:
    # ...
    if something:
        found = True

By user input:

code.py
while True:
    answer = input("Continue? (y/n): ")
    if answer == "n":
        break

Quick Reference

Basic while:

code.py
while condition:
    # do this

Forever (use with break):

code.py
while True:
    # do this
    if something:
        break

Stop early:

code.py
break

Skip one:

code.py
continue

Summary

  • while loops repeat while condition is True
  • Always change the condition to avoid infinite loops
  • Use break to stop early
  • Use continue to skip one iteration
  • Good for unknown number of repetitions
  • Use for loops when count is known

What's Next?

Now let's learn how to create reusable code with functions!

SkillsetMaster - AI, Web Development & Data Analytics Courses