While Loops

Carson West

Python 1 Home

While Loops

While loops in Python execute a block of code repeatedly as long as a given condition is true.

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

The loop continues until count is no longer less than 5. We must ensure the condition eventually becomes false to avoid an infinite loop.

Infinite Loops

Important Considerations:

Example with break:

count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

Example with continue:

count = 0
while count < 5:
    count += 1
    if count == 3:
        continue  # Skip printing 3
    print(count)

Related Notes: