Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In programming, repetition is fundamental. When you know in advance exactly how many times a code block must run (e.g. iterating over 50 student records), a for loop is ideal. However, when an action must repeat until an unpredictable condition changes (e.g. waiting for a user to enter the correct password, or streaming sensor data until a connection drops), Python provides the while loop.
A while loop is condition-controlled: it repeatedly evaluates a boolean expression and executes its indented block as long as that expression remains True.
+-------------------------------------------------------------------------------+
| WHILE LOOP REAL-WORLD ANALOGIES |
+-------------------------------------------------------------------------------+
1. THE CHAI TAPRI STOVE BURNER:
- The tea vendor places milk, water, tea leaves, and ginger on the stove.
- State condition: Is the chai boiling?
* WHILE chai_is_boiling == False:
Keep gas burner ON, stir gently, check temperature.
* Once boiling bubbles rise (chai_is_boiling == True):
Exit loop, turn off gas knob, pour into kulhad glasses.
- The vendor does not know the exact millisecond it will boil;
they loop strictly based on the physical condition.
2. STATE BANK OF INDIA (SBI) ATM PIN RETRY ENGINE:
- An ATM customer inserts their debit card.
- State condition: Attempts remaining > 0 and PIN unverified.
* Attempt 1: Incorrect PIN -> attempts left = 2. Loop continues.
* Attempt 2: Incorrect PIN -> attempts left = 1. Loop continues.
* Attempt 3: Incorrect PIN -> attempts left = 0. Loop terminates!
- The ATM blocks the debit card for 24 hours.
+-------------------------------------------------------------------------------+To construct a predictable while loop that terminates cleanly, four components are mandatory:
False.Output:
If the state mutation step is omitted, or if the condition can never logically evaluate to False, Python enters an infinite loop. The program locks up, consuming 100% of a CPU core until forcibly killed.
Ctrl + C (or Cmd + C on macOS) to send a KeyboardInterrupt signal to kill the CPython interpreter process.while True:)Sometimes, an infinite loop is deliberately intended. Modern server daemons, microservices, game engines, and command-line interfaces run inside an infinite loop that continues until an explicit break condition or shutdown signal occurs:
Output:
A sentinel value is a special input value (such as "exit", "quit", or -1) that signals the loop to terminate. This pattern is standard for menu-driven CLI tools and data entry programs:
Output:
| Best Practice (DO) | Dangerous Anti-Pattern (DON'T) |
|---|---|
| DO ensure the control variable advances toward the exit condition on every branch. | DON'T forget to increment counters inside loop bodies, leading to CPU-hanging infinite loops. |
DO use while when the number of iterations depends on runtime input, events, or state. | DON'T use while to iterate over lists or ranges when a for loop is cleaner and safer. |
DO include safety circuit-breakers (e.g. max_iterations = 1000) in critical production loops. | DON'T write complex conditional checks inside while that mutate multiple unrelated variables. |
while loop repeats a block of code as long as its test condition remains True.False, the loop body never executes.while loop requires proper initialization, an exit condition, and a state mutation that eventually makes the condition False.Ctrl + C.while True: idiom coupled with an internal break statement is the standard Python pattern for event loops and sentinel-controlled input processing.If you forget to update your loop counter inside a while loop, the condition remains True forever:
Removing or inserting items in a list while looping over it causes skipped elements:
while loop is False upon first evaluation?A. The loop runs exactly once B. Python raises an IndentationError C. The loop body is skipped entirely, and execution proceeds past the loop D. Python hangs in an infinite loop
A. 1 B. 0 C. -1 D. 3
A. Ctrl + Z B. Ctrl + C C. Ctrl + Shift + Esc D. Alt + F4
A. A variable that stores the memory address of the loop B. A predefined dummy input value used to signal the end of loop iteration C. An integer counter that increments by 2 D. A cryptographic hash guarding the loop body
What behavior will be observed when running this code? A. It outputs 0 1 2 B. It outputs 0 1 2 3 C. It produces an infinite loop printing 0 repeatedly D. It raises a NameError
Simulate the automated charting and ticket confirmation process of the Indian Railways reservation system.
When passengers cancel their confirmed tickets, passengers on the Waiting List (WL) are upgraded sequentially:
current_wl = 5).while loop to simulate cancellations until either:current_wl == 0).Track and print the status on each iteration, and log the final charting status.
In the next lesson, we will continue your Python learning journey with For Loop (13: Loops).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Project: Grading System | For Loop |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.