Python while Loop

1. Basic while Loop

count = 1

while count <= 5:
    print(count)
    count += 1

Executes repeatedly as long as the condition evaluates to True.


2. Decrementing Counter in while Loop

number = 5

while number > 0:
    print(number)
    number -= 1

Commonly used for countdown logic.


3. Using while with User Input

user_input = ""

while user_input != "exit":
    user_input = input("Type 'exit' to stop: ")

Loop continues until a specific input condition is met.


4. Infinite while Loop

Creates an endless loop unless interrupted with break.


5. Breaking a while Loop

break terminates the loop immediately.


6. Using continue in while Loop

Skips the current iteration and proceeds to the next cycle.


7. while Loop with else Clause

The else block runs if the loop ends without encountering break.


8. Simulating do-while Loop Behavior

Python does not have a native do-while, but this pattern replicates it.


9. Nested while Loops

A while loop inside another while loop.


10. Using while for Input Validation

Ensures user input meets required constraints before proceeding.


Last updated