DSPython Logo DSPython

While Loops

Repeat code as long as a certain condition is true.

Python Basics Beginner 30 min

πŸ”„ Introduction: The "Gamer" Analogy

Think about playing a video game like Mario or PUBG. You don't say, "I will play exactly 100 steps." Instead, you play while your health is greater than 0.

This is the core difference between a for loop and a while loop:
1. For Loop: You know exactly how many times to run (e.g., "Watch a 2-hour movie").
2. While Loop: You run until a condition changes (e.g., "Sleep while the alarm hasn't rung").

A while loop checks a condition first. If it's True, it runs the code. Then it checks again. It repeats this cycle until the condition becomes False.

🎯 Topic 1: Anatomy of a while Loop

To build a perfect while loop, you need three ingredients. If you miss one, your program might crash!

[Image of flowchart showing while loop execution flow]

πŸ“ The 3 Ingredients:

  • 1. Initialization: Create a variable to track the loop (e.g., i = 1).
  • 2. Condition: The test that must be True to run (e.g., while i <= 5).
  • 3. Update/Increment: Change the variable so the loop eventually ends (e.g., i = i + 1).

πŸ’» Example: The Counting Bot

# 1. Initialization
battery = 10

# 2. Condition
while battery > 0:
print(f"Robot working... Battery: {battery}%")
# 3. Update (Drain battery) battery = battery - 3

print("System Shutdown.")

# Output:
# Robot working... Battery: 10%
# Robot working... Battery: 7%
# Robot working... Battery: 4%
# Robot working... Battery: 1%
# System Shutdown.

⚠️ The "Dr. Strange" Loop (Infinite Loop)

If you forget step #3 (Update), your variable never changes. The condition remains True forever. The loop runs infinitely until your computer freezes or you force stop it.

βš–οΈ Topic 2: While vs For - The Showdown

Beginners often ask: "Which one should I use?" Here is a simple rule.

For Loop

Use when you know the Number of Iterations (Definite).

  • Iterating a List/Tuple
  • Iterating characters in String
  • Counting 1 to 100

While Loop

Use when the End Point is Unknown (Indefinite).

  • Waiting for User Input
  • Reading file until end
  • Game loop (until Game Over)

πŸ›‘οΈ Topic 3: Real World - Input Validation

The most common use of a while loop is to force a user to enter the correct data. You ask them repeatedly while their input is invalid.

πŸ’» Example: Password Checker

password = ""

# Keep asking UNTIL password is 'secret123'
while password != "secret123":
password = input("Enter Password: ")
if password != "secret123":
print("Wrong! Try again.")

print("Access Granted! Welcome.")

♾️ Topic 4: while True Pattern

Sometimes, programmers intentionally create an infinite loop using while True. This is used in servers, game loops, or when you want to stop based on a complex condition inside the loop using break.

πŸ’» Example: The Shopping Cart

# Loop runs forever until we say 'stop'
while True:
item = input("Enter item to buy (or 'stop' to finish): ")

if item == "stop":
print("Closing receipt...")
break # Emergency Exit!

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

πŸ“š Module Summary

  • While Loop: Repeats code while a condition is True.
  • 3 Parts: Initialize, Condition, Update. Don't forget the update!
  • Use Case: Best for input validation and indefinite iteration.
  • while True: Creates an infinite loop, usually paired with break.

πŸ€” Interview Q&A

Tap on the questions below to reveal the answers.

Yes! Python is one of the few languages that allows an else block with loops. The else block runs ONCE when the condition becomes False. However, if you exit the loop using break, the else block is SKIPPED.

No. Python does not have a built-in do-while loop (which runs at least once). However, you can simulate it using while True: and adding a break condition at the bottom of the loop.

Zero. If the condition is False right at the beginning, the code inside the while loop will never execute, not even once.

A Sentinel Value is a special value used to terminate a loop, like asking the user to type "quit" or "-1" to stop entering data. It acts as a signal to the while loop to stop.