The while Loop in Python 3
π’ Beginner Level | Condition-Driven Iteration
π Definition
The while loop in Python executes an indented block of code repeatedly as long as a test condition evaluates to True.
π€ Purpose
Used when looping depends on a dynamic condition rather than a fixed sequence lengthβsuch as waiting for user input or processing socket connections.
π Multilingual Explanations
English
Python evaluates while condition: before every pass. If false initially, the indented block is skipped entirely.
Hindi
Jab tak condition True rehti hai, while block run hota hai. Indentation (4 spaces) maintain karna zaroori hai.
Marathi
Condition True asel toparyant code block execute hoto.
Hinglish
Condition-based repetition: while attempts < 3: attempts += 1 pattern follow hota hai.
π Syntax & Parameters
while condition:
# Indented body
pass
β‘ Execution Flow
- Evaluate
condition. - If
True, execute indented body. - Re-evaluate
conditionuntil it returnsFalse.
π‘ Progressive Examples
Example 1: Retry Counter
attempts = 0
while attempts < 3:
attempts += 1
print(f"Attempt #{attempts} processed.")
π₯οΈ Expected Output
Attempt #1 processed.
Attempt #2 processed.
Attempt #3 processed.
π Line-by-Line Code Breakdown
attempts = 0: Initializes counter variable.while attempts < 3:: Tests if attempts is strictly less than 3.attempts += 1: Increments state counter.
β οΈ Variations & Edge Cases
Combining while with break allows early exit from infinite loops (while True:).
β Common Beginner Mistakes
Infinite Loop: Forgetting to update state inside the loop body causes an infinite loop hanging the script.
π οΈ Real-World Practical Usage
Game main loops or CLI user interaction loops.
π― Tiered Practice Exercises
- Beginner: Write a `while` loop printing numbers from 5 down to 1.
- Intermediate: Write a `while` loop accumulating user inputs until 'exit' is typed.
- Advanced: Create a `while` loop that calculates the GCD of two numbers using the Euclidean algorithm.