Basic while loop

count = 0

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

# Output: 0, 1, 2, 3, 4

User input loop

while True:
    user_input = input("Enter 'quit' to exit: ")
    if user_input == 'quit':
        break
    print(f"You entered: {user_input}")

Conditional while

number = 10

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

# Output: 10, 8, 6, 4, 2

break and continue

count = 0

while count < 10:
    count += 1
    if count == 5:
        continue  # Skip rest of loop body
    if count == 8:
        break  # Exit loop
    print(count)

# Output: 1, 2, 3, 4, 6, 7

else clause

else runs if loop completes without break:

count = 0

while count < 5:
    print(count)
    count += 1
else:
    print("Loop finished")  # Runs after loop completes

Infinite loops

Be careful—always have a way to exit:

# Dangerous infinite loop:
# while True:
#     print("Forever...")

# Safe infinite loop:
while True:
    user_input = input("Command: ")
    if user_input == 'exit':
        break