Python: for, while, Loops

By Xah Lee. Date: . Last updated: .

For Loop

# creates a list, 1 to 3
aa = range(1, 4)

for xx in aa:
    print(xx)

[see Generate List: range]

While Loop

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

Exit Loop

Use break or continue to exit loop.

break
Exit the loop.
continue
Skip rest of loop code and start the next iteration.
for x in range(1, 10):
    print(x)
    if x == 4:
        break
# prints 1 to 4

Python: Loop