for Loop Fundamentals
Learn how Python for loops work with practical examples. This chapter is designed for beginners as well as AI developers using LangChain, CrewAI, LangGraph, OpenAI SDK, and Machine Learning.
for Loop?
A for loop is a control statement used to execute a block of code repeatedly by iterating over a sequence of values.
Instead of manually writing the same code multiple times, Python automatically repeats the statements for every item inside an iterable.
Imagine a teacher checking attendance for 40 students. Instead of writing the same statement 40 times, the teacher simply goes through the student list one by one.
for Loop?
A for loop helps eliminate repetitive code, making programs shorter, cleaner, and easier to maintain.
| Without Loop | With Loop |
|---|---|
| Write the same code many times. | Write once and repeat automatically. |
| Difficult to maintain. | Easy to update. |
| More chances of mistakes. | Cleaner and reliable. |
| Feature | for Loop | while Loop |
|---|---|---|
| Iterations Known? | ✅ Yes | ❌ Usually No |
| Uses Iterator | ✅ Yes | ❌ No |
| Risk of Infinite Loop | Very Low | High |
| Best For | Collections | Conditions |
General syntax of a Python for loop:
for variable in iterable:
# Code to execute
| Keyword | Meaning |
|---|---|
| for | Starts the loop. |
| variable | Current item. |
| in | Reads items one by one. |
| iterable | Collection being processed. |
Let's print five programming languages.
languages = [
"Python",
"Java",
"C#",
"JavaScript",
"Go"
]
for language in languages:
print(language)
Python
Java
C#
JavaScript
Go
documents = [
"invoice.pdf",
"contract.pdf",
"resume.pdf"
]
for doc in documents:
print(f"Processing {doc}...")
range(stop)
The range(stop) function generates numbers starting from 0 up to stop - 1.
for number in range(5):
print(number)
0
1
2
3
4