Loops
A loop in Python is a control structure that repeats a block of code multiple times, using a for loop to iterate over a sequence or a while loop to repeat as long as a condition stays true.
Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Learn how to make Python repeat tasks automatically using for and while loops.
Loops let you repeat code multiple times without writing it over and over. Instead of writing print("Hello") 100 times, you can use a loop to do it once.
Think of loops like a washing machine cycle. It repeats the same steps (wash, rinse, spin) until the clothes are clean. Your code works the same way!
"Do this 10 times" or "Do this for each item"
Use when you repeat until a condition changes
Before writing loops, build a clear picture of what Python is actually doing each time through. This mental model prevents most beginner loop bugs.
The loop variable is reassigned every iteration
Each time the loop runs, the loop variable gets the next value from the sequence. Python handles this automatically — you just use it.
Everything indented under for or while is the loop body. It runs once per value. Code at the original indentation level runs after the loop finishes.
The loop variable still exists after the loop
After a for loop finishes, the loop variable holds the last value it had. This is sometimes useful — but can also cause bugs if you forget.
The for loop repeats code for each item in a sequence (like a list or range of numbers).
range() generates a sequence of numbers. It's the most common way to repeat code a specific number of times.
The while loop repeats as long as a condition is True . Use it when you don't know exactly how many times to repeat.
An infinite loop runs forever because its condition never becomes False. Your program freezes and you have to force-quit it. Here's how they happen and how to prevent them.
The sentinel value pattern — loop until a special value
A sentinel is a special value that signals "stop". This pattern is everywhere in real programs:
while True: is valid — an intentional infinite loop is fine as long as you have a break condition inside. This pattern is used for menus, game loops, and server request handling.
When writing complex while loops, adding a maximum counter is a professional safety habit — it turns an accidental infinite loop into a detectable bug.
If you can answer "how many times?" → use for If you can answer "until what?" → use while
Five patterns appear in virtually every program that uses loops. Learn to recognise them and you'll be able to solve most loop problems from memory.
Pattern 1: Accumulator — build a running total
Pattern 2: Counter — count items that match a condition
Pattern 3: Filter — collect items that meet a condition
Pattern 5: Transform — build a new list from an old one
You'll soon learn a shorter way to write this using list comprehensions — but the pattern is the same.
Sometimes you need more control over your loops. Python provides two special keywords:
Python has a feature almost no other language has: an else block on loops. It sounds confusing at first, but it solves a real problem elegantly.
The else block runs only if the loop completed without hitting a break . If break was triggered, else is skipped entirely.
Real use case: searching for a prime number factor
You can loop through many types of sequences in Python:
Python includes several built-in functions that make loops dramatically more powerful and readable. These are used constantly in real code.
enumerate() — get the index alongside the value
Without it, you'd need a manual counter variable. With it, Python tracks the index for you:
The start=1 argument makes numbering start at 1 instead of 0 — perfect for user-facing lists.
zip() — loop through two sequences in parallel
zip() pairs up items from two (or more) sequences, giving you one item from each per iteration:
zip() stops at the shortest sequence. If one list has 3 items and another has 5, you get 3 pairs.
reversed() — loop backwards through a sequence
Lists, strings, range() , enumerate() , zip() , and reversed() are all things Python can loop over. The technical term is iterable . Any time you use for x in ___ , the blank must be an iterable.
You can put a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
Outer loop runs once → Inner loop runs completely Outer loop runs again → Inner loop runs completely again ...and so on
A list comprehension is a compact, one-line way to build a list using a loop — and it's one of the most distinctly "Pythonic" features of the language. Once you understand them, you'll use them constantly.
The transformation: for loop → list comprehension
Forgetting to update the condition in while loops
This causes infinite loops! Always change something inside the loop.
range(5) gives 0-4, not 1-5. Use range(1, 6) for 1-5.
This can cause unexpected behavior. Loop through a copy instead.
FizzBuzz is the most famous beginner programming challenge — it's used in real job interviews to test basic loop and condition logic. If you can write FizzBuzz, you understand loops.
Classic FizzBuzz — uses: for loop, range(), modulo, if/elif/else
Extended version — adds: accumulator, counter, filter patterns
Challenge: Can you rewrite the FizzBuzz output using a list comprehension? Hint: you'll need the ternary operator from Lesson 4.
Congratulations! You've completed the Python basics. You now know:
Next up: Functions - learn how to organize your code into reusable blocks!
🏆 Beginner Track Complete! You've mastered the fundamentals!
Variables, operators, conditions, and loops — these 5 lessons are the foundation of all programming. Every Python developer in the world uses these exact same tools every single day.
🚀 Up next: Functions — learn to package your code into reusable blocks so you never repeat yourself.
Practice quiz
Which loop is best when you know exactly how many times to repeat?
- while loop
- do-while loop
- for loop
- repeat loop
Answer: for loop. A for loop is used when you know how many times (or which items) to iterate over.
What numbers does range(5) produce?
- 0, 1, 2, 3, 4
- 1, 2, 3, 4, 5
- 0, 1, 2, 3, 4, 5
- 5
Answer: 0, 1, 2, 3, 4. range(5) goes from 0 to 4 — the stop value is NOT included.
What does range(2, 6) produce?
- 2, 3, 4, 5, 6
- 2, 6
- 0, 1, 2, 3, 4, 5
- 2, 3, 4, 5
Answer: 2, 3, 4, 5. range(start, stop) gives start up to stop-1: 2, 3, 4, 5.
What does range(0, 10, 2) produce?
- 0, 2, 4, 6, 8, 10
- 0, 2, 4, 6, 8
- 0, 1, 2, ..., 10
- 2, 4, 6, 8
Answer: 0, 2, 4, 6, 8. The step of 2 yields even numbers from 0 up to (but not including) 10.
What does the 'break' keyword do inside a loop?
- Exits the loop immediately
- Skips the current iteration
- Restarts the loop
- Pauses the loop
Answer: Exits the loop immediately. break exits the loop immediately, skipping any remaining iterations.
What does the 'continue' keyword do?
- Exits the loop
- Ends the program
- Skips to the next iteration
- Repeats the current item
Answer: Skips to the next iteration. continue skips the rest of the current iteration and moves to the next one.
What causes an infinite while loop?
- Using range()
- The condition never becoming False
- Using break
- Too many items
Answer: The condition never becoming False. If the while condition never becomes False (e.g. you forget to update the variable), it runs forever.
Which loop should you use to 'keep asking until the user types quit'?
- for loop
- range loop
- nested loop
- while loop
Answer: while loop. A while loop repeats until a condition changes — ideal when you don't know how many iterations.
After 'for fruit in ["a", "b", "c"]:' finishes, what value does fruit hold?
- 'a'
- 'c'
- None
- It no longer exists
Answer: 'c'. The loop variable keeps the last value it took, 'c', after the loop ends.
Is 'while True:' with a break inside considered valid Python?
- No, it always errors
- Only in functions
- Yes, an intentional infinite loop with a break exit is fine
- Only with range()
Answer: Yes, an intentional infinite loop with a break exit is fine. while True: is valid as long as a break (or return) eventually exits it.