Python Tutorial: Loops
Stop writing the same code ten times. for and while loops do the repetition for you.
Computers love repetition
Printing 100 names, summing 1000 numbers, retrying until the user enters valid input — all of that needs loops.
`for` loops over a sequence. `while` loops until a condition is false. Together they handle almost everything. Twelve steps.
What you'll learn in this Python loops tutorial
This interactive Python tutorial has 11 hands-on exercises. Estimated time: 20 minutes.
- Computers love repetition — Imagine you need to print the names of 100 students. Without loops, you would write 100 `print()` calls. By hand. And th…
- range() — count for me — `range(n)` generates numbers from 0 to n-1. You don't see them all at once — Python creates them one at a time.
- Strings are sequences too — Here is something that surprises beginners: strings are sequences of characters. You can loop over them just like lists.
- enumerate() — index AND value — Sometimes you need to know the position (index) of each item while looping. You could track it manually with a counter, …
- while — loop until something changes — `for` loops are great when you know what you're looping over. `while` is for when you don't know how many times you'll l…
- break — exit early — `break` immediately exits the loop — even if there are items left.
- continue — skip and keep going — `continue` skips the rest of the current iteration and jumps straight to the next one. The loop keeps going — you're jus…
- zip() — two lists at once — What if you have two related lists — names and scores — and you want to loop over both at the same time?
- Nested loops — A loop inside a loop. The inner loop runs completely for every single iteration of the outer loop.
- List comprehension — a loop in one line — Python has a beautiful shortcut for creating lists from loops:
- FizzBuzz — the classic challenge — Almost every programming interview has this question. Now you have everything you need to ace it.
Python Loops concepts covered
- Computers love repetition