Python: Loop

By Xah Lee. Date: . Last updated: .

For Loop

for xx in range(1, 4):
    print(xx)
# 1
# 2
# 3

While Loop

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

# 1
# 2
# 3
# 4

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