Python Tutorial Series

Chapter 1 - Python 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.

📚 Chapter Contents

  • 1. What is a Python for Loop?
  • 2. Why Use a for Loop?
  • 3. for Loop vs while Loop
  • 4. Basic Syntax
  • 5. Basic for Loop Example
  • 6. Using range(stop)

1. What is a Python 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.

What can Python iterate over?
  • Lists
  • Tuples
  • Strings
  • Dictionaries
  • Sets
  • Files
  • range()
Real-Life Example

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.

Python does exactly the same thing. It automatically moves to the next item until every element has been processed.

2. Why Use a 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.
Most Common Uses
  • Reading files
  • Processing API responses
  • Machine Learning datasets
  • Document processing
  • Generating reports
  • AI prompt processing

3. for Loop vs while Loop

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
AI Developer Tip Most AI applications use for loops because they process collections such as prompts, documents, embeddings, API responses, and datasets.

4. Basic Syntax

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.

5. Basic for Loop Example

Let's print five programming languages.

languages = [
    "Python",
    "Java",
    "C#",
    "JavaScript",
    "Go"
]

for language in languages:
    print(language)
Output
Python
Java
C#
JavaScript
Go
AI Example
documents = [
    "invoice.pdf",
    "contract.pdf",
    "resume.pdf"
]

for doc in documents:
    print(f"Processing {doc}...")

6. Using range(stop)

The range(stop) function generates numbers starting from 0 up to stop - 1.

for number in range(5):
    print(number)
Output
0
1
2
3
4
Remember
  • The first number is always 0.
  • The stop value is never included.
  • Very common for repeating a task a fixed number of times.