foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Python
  • Understand when to use while loops vs for loops
  • Write while loops that run until a condition changes
  • Use break to exit loops early
  • Use continue to skip iterations

While Loops and Loop Control

Sometimes you don't know in advance how many times you need to repeat something. A for loop is great when you're iterating over a list of 10 items. But what if you're asking users for input until they type "quit"? Or waiting for a game to end? Or processing data until you find what you're looking for?

This is where while loops shine. They keep running as long as a condition is true – whether that's 3 times, 100 times, or until something specific happens. Combined with break and continue, they give you complete control over your program's flow.


The while Loop

A while loop repeats as long as its condition remains True.

Anatomy of a while Loop


                    while Loop Structure                          

                                                                  
   while condition:        ← Check condition BEFORE each run     
       # do something      ← Loop body (indented)                
       # update something  ← Important: change the condition!    
                                                                  
   next_code()             ← Runs after loop ends                
                                                                  
    If condition never becomes False → Infinite loop!          
                                                                  

Visual Flow


                    while Loop Flow                               

                                                                  
                                              
             Check Condition                           
                                             
                                                                
                                             
                                                              
                                          
                True            False                       
                                          
                                                              
                                          
              Run Loop        Exit Loop                     
                Body                                        
                                          
                                                               
                                                        
                                                                  

Simple Countdown Example

countdown = 5

while countdown > 0:
    print(countdown)
    countdown -= 1  # Don't forget this!

print(" Liftoff!")

Output:

5
4
3
2
1
 Liftoff!

What happens:

  1. countdown = 5: condition 5 > 0 is True → run body
  2. Print 5, then countdown = 4: condition 4 > 0 is True → run body
  3. ... continues until countdown = 0
  4. 0 > 0 is False → exit loop

for vs while: When to Use Each


                   for vs while Decision Guide                    

                                                                  
   Use FOR when:                                                  
    Iterating over a sequence (list, string, range)            
    You know how many times to repeat                          
    Processing each item in a collection                       
                                                                  
   Use WHILE when:                                                
    You don't know how many iterations needed                  
    Repeating until a condition changes                        
    Waiting for user input or external events                  
    Implementing game loops or continuous processes            
                                                                  

Comparison Examples

# FOR: Known iterations
# "Process these 5 specific items"
numbers = [10, 20, 30, 40, 50]
for num in numbers:
    print(num)

# WHILE: Unknown iterations
# "Keep asking until they say yes"
answer = ""
while answer != "yes":
    answer = input("Do you agree? (yes/no): ")
print("Thank you for agreeing!")

The Infinite Loop Trap

The most common while loop mistake is forgetting to update the condition:

#  DANGER: Infinite loop!
count = 0
while count < 5:
    print("Hello!")
    # Oops! We never change count!
    # This prints "Hello!" forever...

#  CORRECT: Update the condition
count = 0
while count < 5:
    print("Hello!")
    count += 1  # Now it will stop!

How to Stop an Infinite Loop

If you accidentally create one:

  • In the terminal: Press Ctrl + C
  • In an IDE: Click the stop button

Intentional Infinite Loops

Sometimes infinite loops are useful with break:

# Menu system - runs until user chooses to exit
while True:
    print("\n1. Play Game")
    print("2. View Score")
    print("3. Exit")
    
    choice = input("Choose: ")
    
    if choice == "3":
        print("Goodbye!")
        break  # Exit the loop
    elif choice == "1":
        print("Playing game...")
    elif choice == "2":
        print("Score: 100")

break: Emergency Exit

break immediately exits the loop, no matter what the condition says.

Real-World Analogy

Think of break like finding what you're looking for while shopping. You don't need to check every aisle once you've found your item – you go straight to checkout!

break Example

# Search for a number
numbers = [4, 8, 15, 16, 23, 42]
target = 16

for num in numbers:
    print(f"Checking {num}...")
    if num == target:
        print(f"Found {target}!")
        break  # Stop searching
    
print("Search complete")

Output:

Checking 4...
Checking 8...
Checking 15...
Checking 16...
Found 16!
Search complete

Notice: 23 and 42 were never checked!

break with while

# ATM withdrawal - max 3 attempts
attempts = 0
correct_pin = "1234"

while True:
    pin = input("Enter PIN: ")
    attempts += 1
    
    if pin == correct_pin:
        print(" Access granted!")
        break
    
    if attempts >= 3:
        print(" Too many attempts. Card blocked.")
        break
    
    print(f"Wrong PIN. {3 - attempts} attempts remaining.")

⏭ continue: Skip and Move On

continue skips the rest of the current iteration and moves to the next one.

Real-World Analogy

Imagine reviewing job applications. If an applicant doesn't meet the minimum requirements, you skip to the next application without reading the rest. That's continue!

continue Example

# Print only even numbers
for num in range(1, 11):
    if num % 2 != 0:  # If odd
        continue      # Skip to next number
    print(num)

# Output: 2, 4, 6, 8, 10

Processing with Exceptions

scores = [85, -1, 92, 78, -1, 95, 88]

print(" Valid Scores:")
total = 0
count = 0

for score in scores:
    if score < 0:  # Invalid score
        print(f"  Skipping invalid score: {score}")
        continue
    
    print(f"   {score}")
    total += score
    count += 1

if count > 0:
    average = total / count
    print(f"\nAverage of valid scores: {average:.1f}")

break vs continue Visual


                 break vs continue                                

                                                                  
   BREAK:                    CONTINUE:                           
                                                                  
   Iteration 1               Iteration 1                         
   Iteration 2               Iteration 2                         
   BREAK!     CONTINUE!                     
   Iteration 3 (skip)       Iteration 3     (skipped)          
   Iteration 4 (skip)       Iteration 4  (runs!)            
   Iteration 5 (skip)       Iteration 5    (runs!)              
         ↓                                                      
   Exit loop                                         
                                                                  
   break = "I'm done with this loop entirely"                    
   continue = "Skip this one, try the next"                      
                                                                  

Common while Loop Patterns

Pattern 1: Input Validation

# Keep asking until valid input
while True:
    age_str = input("Enter your age: ")
    
    if age_str.isdigit():
        age = int(age_str)
        if 0 < age < 150:
            break
    
    print("Please enter a valid age (1-149)")

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

Pattern 2: Counter-Controlled

# Count until condition met
count = 0
total = 0

while total < 100:
    total += 10
    count += 1
    print(f"Step {count}: Total = {total}")

print(f"Reached {total} in {count} steps")

Pattern 3: Sentinel Value

# Process until special value
print("Enter numbers (type 'done' to finish):")
numbers = []

while True:
    value = input("> ")
    
    if value.lower() == "done":
        break
    
    if value.isdigit():
        numbers.append(int(value))

print(f"You entered: {numbers}")
if numbers:
    print(f"Sum: {sum(numbers)}")

Practical Examples

Example 1: Guessing Game

import random

secret = random.randint(1, 100)
attempts = 0

print(" Guess the Number (1-100)")
print("-" * 30)

while True:
    guess = input("Your guess: ")
    
    if not guess.isdigit():
        print("Please enter a number!")
        continue
    
    guess = int(guess)
    attempts += 1
    
    if guess < secret:
        print(" Too low! Try higher.")
    elif guess > secret:
        print(" Too high! Try lower.")
    else:
        print(f" Correct! You got it in {attempts} attempts!")
        break

Example 2: Simple Login System

users = {
    "alice": "password123",
    "bob": "secure456"
}

max_attempts = 3
attempts = 0

print(" Login System")
print("=" * 30)

while attempts < max_attempts:
    username = input("Username: ")
    password = input("Password: ")
    
    if username in users and users[username] == password:
        print(f"\n Welcome, {username}!")
        break
    
    attempts += 1
    remaining = max_attempts - attempts
    
    if remaining > 0:
        print(f" Invalid credentials. {remaining} attempts remaining.\n")
    else:
        print("\n Account locked. Too many failed attempts.")

Example 3: Progress Tracker

goal = 10000  # Steps goal
current_steps = 0
day = 0

print(" 10,000 Steps Challenge")
print("-" * 30)

while current_steps < goal:
    day += 1
    
    # Simulate daily steps (in real app, this would be actual input)
    daily_steps = int(input(f"Day {day} - Steps walked: "))
    
    if daily_steps < 0:
        print("Steps can't be negative!")
        continue
    
    current_steps += daily_steps
    remaining = max(0, goal - current_steps)
    progress = min(100, (current_steps / goal) * 100)
    
    print(f"  Total: {current_steps} | Progress: {progress:.1f}% | Remaining: {remaining}")
    
    if current_steps >= goal:
        print(f"\n Goal reached in {day} days! You walked {current_steps} steps!")

Key Takeaways


                   Remember These Points                          

                                                                  
   while loops repeat while condition is True                  
     while condition:                                             
         (body)                                                   
                                                                  
   Always update something to avoid infinite loops!             
                                                                  
   break: Exit the loop immediately                            
                                                                  
  ⏭ continue: Skip to next iteration                            
                                                                  
   Use for: known iterations (lists, ranges)                   
     Use while: unknown iterations (until condition changes)     
                                                                  
   while True + break = common pattern for menus/input         
                                                                  

What's Next?

Congratulations! You've completed the Control Flow module. You can now make decisions with if/elif/else and repeat actions with for and while loops. These are fundamental building blocks that you'll use in every program you write.

In the next module, we'll explore Data Structures – learning about lists, tuples, dictionaries, and sets. These let you organize and manage collections of data efficiently!

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service