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

  1. Evaluate condition.
  2. If True, execute indented body.
  3. Re-evaluate condition until it returns False.

πŸ’‘ 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

  1. Beginner: Write a `while` loop printing numbers from 5 down to 1.
  2. Intermediate: Write a `while` loop accumulating user inputs until 'exit' is typed.
  3. Advanced: Create a `while` loop that calculates the GCD of two numbers using the Euclidean algorithm.