← Python tutorial

Python

Loops

A for loop steps through a sequence, often the result of range(n), which produces the numbers 0 up to (not including) n.

Example: summing a range

total = 0
for i in range(1, 6):
    total += i

print("Total:", total)
Total: 15

range(1, 6) produces 1, 2, 3, 4, 5, the second number is the stopping point, not included, which trips up nearly every beginner at least once. A while loop, by contrast, repeats as long as its condition stays true, and is the better tool whenever you don't know the number of iterations in advance.

Example
total = 0
for i in range(1, 6):
    total += i

print("Total:", total)
Output
Total: 15
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Closes Nov 30

Enroll in Backend Development

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account