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.
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.
What You'll Learn in This Lesson
What Are 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
🧠 How Loops Execute: The Mental Model
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.
1. The for Loop
The for loop repeats code for each item in a sequence (like a list or range of numbers).
Part
Description
for
Keyword that starts the loop
variable
Holds the current item (you choose the name)
in
Keyword connecting variable to sequence
sequence
What to loop over (list, range, string, etc.)
:
Required colon at the end
2. The range() Function
range() generates a sequence of numbers. It's the most common way to repeat code a specific number of times.
Syntax
What It Produces
Example
range(stop)
0 to stop-1
range(5) → 0,1,2,3,4
range(start, stop)
start to stop-1
range(2, 6) → 2,3,4,5
range(start, stop, step)
start to stop-1, by step
range(0, 10, 2) → 0,2,4,6,8
3. The while Loop
The while loop repeats as long as a condition is True . Use it when you don't know exactly how many times to repeat.
♾️ Infinite Loops and Writing Safe while Loops
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.
4. When to Use for vs while
Use for
Use while
You know how many times to repeat
You don't know when to stop
Looping through a list/string
Waiting for user input
"Do this 10 times"
"Keep going until X happens"
for i in range(10):
while not done:
If you can answer "how many times?" → use for If you can answer "until what?" → use while
🧰 Loop Patterns: The Essential Toolkit
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.
5. Loop Control: break and continue
Sometimes you need more control over your loops. Python provides two special keywords:
🔀 The else Clause on Loops — Python's Hidden Feature
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
6. Looping Through Different Data Types
You can loop through many types of sequences in Python:
Data Type
What You Get Each Iteration
List
Each item in the list
String
Each character
Dictionary
Each key (or use .items() for key-value pairs)
range()
Each number in the sequence
🔧 Loop Helpers: enumerate() , zip() , and reversed()
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.
7. Nested Loops (Loop Inside a Loop)
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
⚡ List Comprehensions: The Pythonic Way to Build Lists
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
Common Mistakes to Avoid
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.
8. Practical Examples
Example 1: Sum of Numbers
Example 2: Find an Item
Example 3: Password Attempts
Mini-Project: FizzBuzz and Number Analysis
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.
- • Count from 1 to 100
- • If a number is divisible by 3 → print "Fizz"
- • If a number is divisible by 5 → print "Buzz"
- • If divisible by both 3 and 5 → print "FizzBuzz"
- • Otherwise → print the number itself
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.
Summary: Quick Reference
Concept
What It Does
Loop through a sequence
for x in list:
while
Loop while condition is True
while x < 10:
Generate number sequence
range(1, 10, 2)
break
Exit loop immediately
if done: break
continue
Skip to next iteration
if skip: continue
enumerate()
Get index + value
for i, x in enumerate(list):
Beginner Track Complete!
Congratulations! You've completed the Python basics. You now know:
- Variables and data types
- Operators and expressions
- Control flow with if/elif/else
- Loops with for and while
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.
Continue this course
- Previous: Control Flow - If/Else
- Next: Functions