CodeNest

Repeating with loops

A for loop repeats a block for each item in a sequence. range(n) produces the numbers 0 to n - 1, and range(a, b) produces a to b - 1:

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

A while loop repeats as long as a condition holds:

count = 3
while count > 0:
    print(count)
    count -= 1      # same as count = count - 1

Try it

Print the squares of the numbers 1 to 5, one per line, followed by the word Done:

1
4
9
16
25
Done
Python in-browser · Python 3.13
Next
Loading editor…

Press Ctrl/ + Enter or click Run to see the output here.