What Is a For Loop?
A for loop is like an automatic counter machine that takes a list of items, like numbers, names, or anything and checks or uses each item one after another automatically.
We don’t need to create counters manually or manage indexes; Python allows the loop to directly access each item in a sequence.
Python’s for loop works with many data types, such as:
- lists
- tuples
- strings
- sets
- dictionaries
- sequences
Why We Use For Loops In Python?
We use a for loop in Python because we don’t write the same code line again and again; a for loop automatically runs that code for each element.
Python directly provides you with each element, making your code more natural and easier to understand.
If you have a list, tuple, string, or dictionary, a for loop helps you handle each element one by one.
Syntax of a For Loop
for variable in sequence:
# Code block to execute
Explaining Each part:
1) variable: This is a placeholder for one value from the sequence during each iteration. You can add any name you want in a loop.
Imagine you have 5 chocolates. When you pick one chocolate, you call it chocolate. Next, you pick the second chocolate, again you call it chocolate, and it will happen continually.
Here, chocolate is the variable and represents one chocolate at a time.
for chocolate in chocolates:
print(chocolate)
2) sequence: A sequence is the group of items that you want to loop through.
For example, your chocolates are kept in a box [“Dairy Milk”, “KitKat”, “5 Star”]. This whole box is the sequence. So Python takes one chocolate at a time from this sequence.
chocolates = ["Dairy Milk", "KitKat", "5 Star"] # <-- this is the sequence
for chocolate in chocolates: # chocolates = sequence
print(chocolate)
- sequence = many items
- variable = one item at a time from that sequence
Example of For Loop
tasks = ["Wash dishes", "Read a book", "Write notes", "Drink water"]
for task in tasks:
print(f"Task: {task} — Status: Pending")
Output:
Task: Wash dishes — Status: Pending
Task: Read a book — Status: Pending
Task: Write notes — Status: Pending
Task: Drink water — Status: Pending
For Loop Iterating Over Different Data Types
1. Strings
A string refers to a sequence of characters. When you loop through it, Python gives you one character at a time.
word = "Learn"
for ch in word:
print("Letter seen:", ch)
Output:
Letter seen: L
Letter seen: e
Letter seen: a
Letter seen: r
Letter seen: n
- Python takes each character in “learn” and assigns it to ch one by one, so the loop prints every letter individually.
2. Tuples
Tuples store fixed sets of items, so the for loop visits each element in the tuple without modifying it.
marks = (88, 76, 92, 81)
for score in marks:
print("Scored:", score)
Output:
Scored: 88
Scored: 76
Scored: 92
Scored: 81
3. Dictionaries
Dictionaries store data in key-value pairs. It means you can loop through only keys, values, or both together.
profile = {"user": "Ravi", "level": 3, "points": 250}
for key, val in profile.items():
print(f"{key} → {val}")
Output:
user → Ravi
level → 3
points → 250
4. Iterating With range()
range() creates a sequence of numbers that is commonly used when you need repeated actions a fixed number of times. For example:
for num in range(1, 6): # 1 to 5
print("Step:", num)
Output:
Step: 1
Step: 2
Step: 3
Step: 4
Step: 5
How To Use Else with For Loops?
We can also use else with a for loop. The else part runs only after the loop finishes normally, it means:
- The loop iterated through the entire sequence without a break,
- And no early exit happened.
For example:
for attempt in range(1, 4):
print("Trying attempt number:", attempt)
else:
print("All attempts completed without interruption.")
Output:
Trying attempt number: 1
Trying attempt number: 2
Trying attempt number: 3
All attempts completed without interruption.
How To Use a For Loop With Break and Continue Statement?
a) Break Statement
The break statement immediately stops the loop, even if there are remaining items in the sequence.
It’s commonly used when you find what you’re searching for or when further iterations are unnecessary. For example:
for num in range(10):
if num == 5:
print("Stopping because we reached 5.")
break
print("Current number:", num)
Output:
Current number: 0
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Stopping because we reached 5.
b) Continue Statement
The continue statement does not stop the loop. Instead, it skips the current iteration and moves to the next one.
Example of continue statement:
for num in range(5):
if num == 2:
print("Skipping number 2.")
continue
print("Value:", num)
Output:
Value: 0
Value: 1
Skipping number 2.
Value: 3
Value: 4
Nested For Loops In Python
- A nested for loop means using one for loop inside another.
- It is useful when you want to work with data that has multiple levels, like lists inside lists, grids, tables, or any structure where each item contains more items.
Example:
batches = [
["Aarav", "Mia"],
["Kabir", "Zoya"],
["Rohan", "Isha"]
]
for group in batches: # Outer loop → each batch
for student in group: # Inner loop → each student inside the batch
print("Student:", student)
Output:
Student: Aarav
Student: Mia
Student: Kabir
Student: Zoya
Student: Rohan
Student: Isha
Real-World Use Cases of For Loops in Projects
Let’s see the examples where we can use a for loop in real projects.
1. Processing User Input Data
- Developers add validation when a website form sends multiple fields, like name, age, email, etc.
- For example:
form_data = {
"name": "Parthik",
"email": "example@mail.com",
"age": "22"
}
errors = []
for field in form_data:
if form_data[field] == "":
errors.append(f"{field} cannot be empty")
if errors:
print("Errors found:", errors)
else:
print("Form submitted successfully!")
Output:
Form submitted successfully!
#None of the values in form_data are empty (""), there are no errors.
2. Reading Files Line by Line (Log Analysis)
- We can also use a for loop to analyze server logs to detect errors.
- For example: Scan the log file for “ERROR”
log_file = [
"INFO: Server started",
"WARNING: Low memory",
"ERROR: Database not connected",
"INFO: User logged in"
]
for line in log_file:
if "ERROR" in line:
print("Found issue →", line)
Output:
Found issue → ERROR: Database not connected
- What is type casting in Python?
- What are numbers in Python?
- How we can use data types in Python?
- What are variables in Python?
- What are strings in Python?

M.Sc. (Information Technology). I explain AI, AGI, Programming and future technologies in simple language. Founder of BoxOfLearn.com.