🐍 While Loop

loop

Good to know

⭐️ A while loop repeats as long as its condition stays True. Be careful: if the condition never becomes False, you create an infinite loop.


Basic While Loop

Repeats until the condition becomes False.

i = 0
while i < 5:
    print(i)
    i += 1
# Prints 0,1,2,3,4

Using continue Inside a While Loop

continue skips the rest of the loop and goes to the next iteration.

i = 0
while i < 6:
    i += 1
    if i % 2 == 0:
        continue  # skip even numbers
    print(i)

While Loop With Else

The else block runs only if the loop finishes normally (no break).

i = 0
while i < 3:
    print(i)
    i += 1
else:
    print("Finished!")

Infinite Loop (Be Careful!)

Useful in games, servers, or programs waiting for input.

while True:
    user = input("Type 'quit' to stop: ")
    if user == "quit":
        break

Common Pattern: Loop Until Valid Input

answer = ""
while answer != "yes":
    answer = input("Do you agree? yes/no: ")
 
print("Thanks!")