Mastering Python For Loops: Iteration and Range Explained
Learn how to use Python for-loops to automate repetitive tasks. Master the range() function, string iteration, and clean code patterns for your CLI projects.

Previously in this course, we covered Logical Operators, which allowed us to build sophisticated conditional checks. Now, we add iteration to our toolkit.
So far, if you wanted to print "Hello" five times, you would have written print() five times. That’s inefficient and prone to error. In software engineering, we follow the DRY principle: Don't Repeat Yourself. Loops are the primary way we enforce this, allowing us to execute the same block of code multiple times without manual duplication.
The Power of Iteration
A for loop in Python is designed to iterate over "iterables"—sequences of data like strings or ranges of numbers. Instead of manually managing a counter variable, you define a target variable that takes on the value of each item in the sequence, one by one.
Iterating Over Strings
Strings are sequences of characters. A for loop treats them as a collection, letting you process each character individually.
PYTHON# Iterating through a string name = "Backend" for letter in name: print(f"Current character: {letter}")
In this example, the variable letter acts as a placeholder. During the first cycle of the loop, letter is "B". During the second, it becomes "a", and so on until the end of the string.
Controlling Repetition with range()
When you don't have a sequence but simply need to repeat an action a specific number of times, Python provides the range() function. It generates a sequence of numbers automatically.
range(start, stop) creates numbers starting at start and ending just before stop. If you provide only one argument, like range(5), Python assumes you mean range(0, 5).
PYTHON# Executing code 5 times for i in range(5): print(f"Executing task number {i + 1}")
Pro-tip: We typically use the variable name i (short for index) as a convention when the variable itself doesn't hold semantic meaning, only tracking the iteration count.
Practical Application: Data Collector CLI
In our Data Collector CLI, we previously captured three data points manually. Let's imagine we want to collect five data points instead. Instead of writing five input blocks, we use a loop to streamline the process.
PYTHON# Collecting 5 data entries using a loop print("--- Data Collector ---") for i in range(5): data = input(f"Enter data point {i + 1}: ") print(f"Captured: {data}") print("Collection complete.")
This drastically reduces the amount of code required and makes the tool easily scalable; if you need to collect 100 points, you just change the number in range().
Hands-on Exercise
Modify your existing data collection script. Instead of asking for a specific number of items manually, write a script that:
- Asks the user how many items they want to enter.
- Uses
range()to loop that exact number of times. - Prints a confirmation message for each entry.
Common Pitfalls
- Off-by-one errors: Remember that
range(5)creates values 0, 1, 2, 3, and 4. It stops before 5. If you need to count from 1 to 5, userange(1, 6). - Indentation errors: Like
if-elseblocks, everything inside yourforloop must be indented. If the code following the loop isn't indented, it will run after the loop completes; if it is indented, it runs as part of the loop. - Modifying the sequence: Avoid changing the variable you are iterating over inside the loop. It can lead to unpredictable behavior and infinite loops.
Frequently Asked Questions
Q: Can I loop backwards using range()?
Yes. Use a third argument for the step: range(5, 0, -1) will count 5, 4, 3, 2, 1.
Q: What is the difference between for and while loops?
A for loop is ideal when you know how many times you need to iterate (or you are processing a defined sequence). A while loop is better when you need to repeat something until a specific condition is met (like waiting for a user to type "exit").
Q: Can I stop a for loop early?
Yes, you can use the break statement to exit the loop immediately if a specific condition is met.
Recap
We’ve learned that for loops are the engine of repetitive tasks in Python. By leveraging range() for counter-based repetition and direct iteration for string processing, you can write cleaner, more efficient code. You’ve successfully moved from hard-coding inputs to dynamic, scalable data collection.
Up next: Introduction to Lists, where we store multiple items in a single variable.
Work with me

AI Automation & Agentic Workflow Development
Automate the repetitive work eating your time — content pipelines, data workflows, and agentic AI tasks that run themselves.

CI/CD Pipeline & Docker Containerization
Ship with confidence: automated CI/CD pipelines and Docker setups so every push is tested and deployed — no more manual, error-prone releases.

