How to Write a For Loop in Python (Beginners)
How to Write a For Loop in Python: A Beginner’s Guide
Introduction
If you are just starting out with Python, one of the most powerful tools you will use every single day is the for loop. A for loop lets you repeat a block of code multiple times without having to write the same lines over and over again. Instead of copying and pasting the same instruction ten times, you write it once and let Python handle the repetition for you.
In this guide, you will learn exactly how to write a for loop in Python, understand the syntax, and see real examples you can try right now. Whether you want to loop through a list of names, count numbers, or process data, this article has you covered. No prior experience beyond basic Python setup is required.
Understanding the Basic For Loop Syntax
Before writing your first for loop, it helps to understand what it is actually doing. A for loop in Python iterates over a sequence — meaning it goes through each item in a collection one by one and runs a block of code for each item.
Here is the basic syntax of a for loop in Python:
for variable in sequence:
# code to run for each item
Let’s break this down piece by piece:
- for — This keyword tells Python you are starting a loop.
- variable — This is a temporary name that holds the current item during each pass through the loop. You can name it anything you like.
- in — This keyword connects the variable to the sequence you want to loop through.
- sequence — This is the collection of items you want to iterate over. It can be a list, a string, a range, a tuple, and more.
- colon (:) — The colon signals the start of the loop body.
- indented code block — Everything indented underneath the for statement is part of the loop and will run once for each item.
Here is your very first working example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Python goes through the list, assigns each item to the variable fruit one at a time, and runs print(fruit) for each one. That is the core idea behind every for loop you will ever write.
Using the range() Function in a For Loop
One of the most common ways to use a for loop in Python is with the built-in range() function. The range() function generates a sequence of numbers, which makes it perfect when you want to repeat something a specific number of times or work with numbered indexes.
Here is the basic usage:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Notice that range(5) starts at zero and goes up to but does not include five. This is called zero-based indexing and is standard in Python.
You can also control the start, stop, and step values in range():
# range(start, stop, step)
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
This loop starts at 1, stops before 10, and counts up by 2 each time. The range() function gives you a lot of flexibility for counting loops without needing to create a list manually.
Another common pattern is using range() to loop a set number of times:
for i in range(3):
print("Hello, Python!")
Output:
Hello, Python!
Hello, Python!
Hello, Python!
Even if you do not need the loop variable i, you can still use range() to control how many times the loop runs. By convention, programmers often use an underscore _ as the variable name when the loop variable is not needed: for _ in range(3):.
Looping Through Strings, Lists, and Dictionaries
The real power of Python for loops comes from how naturally they work with different data types. Let’s look at a few common examples you will encounter as a beginner.
Looping through a string: In Python, a string is a sequence of characters, so you can loop through each character directly.
word = "Python"
for letter in word:
print(letter)
Output:
P
y
t
h
o
n
Looping through a list with index using enumerate(): Sometimes you need both the item and its position in the list. The enumerate() function gives you both at once.
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)
Output:
0 red
1 green
2 blue
Looping through a dictionary: Dictionaries store key-value pairs. You can loop through the keys, values, or both.
student = {"name": "Alice", "age": 20, "grade": "A"}
for key, value in student.items():
print(key, ":", value)
Output:
name : Alice
age : 20
grade : A
Using .items() lets you unpack both the key and the value in each iteration, which is a very clean and readable pattern in Python.
Nested for loops: You can also place one for loop inside another. This is useful when working with grids or multi-dimensional data.
for i in range(1, 4):
for j in range(1, 4):
print(i, "x", j, "=", i * j)
This prints a simple multiplication table. Just be careful — nested loops can slow your program down if the sequences are very large.
Common Beginner Mistakes to Avoid
Now that you know how to write a for loop, here are a few common mistakes beginners make and how to avoid them.
Forgetting the colon: The colon at the end of the for line is required. Leaving it out will cause a SyntaxError. Always double-check your for loop header ends with :.
Incorrect indentation: Python uses indentation to define code blocks. Everything inside the loop must be indented by the same amount — typically four spaces. Mixing tabs and spaces or using inconsistent indentation will cause an IndentationError.
Modifying a list while looping through it: Changing the size of a list while iterating over it can cause unexpected behavior. If you need to modify a list, consider looping over a copy: for item in my_list[:]:.
Using the wrong variable name: If you create a loop variable called item but accidentally type items inside the loop body, Python will throw a NameError. Keep your variable names consistent and descriptive.
Frequently Asked Questions
What is the difference between a for loop and a while loop in Python?
A for loop is used when you know in advance how many times you want to iterate, or when you are going through a specific sequence like a list or range. A while loop keeps running as long as a condition remains true, making it better suited for situations where the number of iterations is not known upfront. For most beginner tasks involving lists and ranges, a for loop is the right choice.
Can I use a for loop without a list or range?
Yes! In Python, any iterable object can be used in a for loop. This includes strings, tuples, sets, dictionaries, file objects, and even custom objects that implement the iterator protocol. If Python can step through it one item at a time, you can use it in a for loop.
How do I stop a for loop early in Python?
You can exit a for loop before it finishes by using the break statement. When Python encounters break, it immediately stops the loop and moves on to the next line of code after the loop. For example: if item == "stop": break. You can also use continue to skip the current iteration and move to the next one without stopping the loop entirely.
Conclusion
The for loop is one of the foundational building blocks of Python programming. Once you understand how to write a for loop and how it moves through sequences, you unlock the ability to process data, automate repetitive tasks, and build more complex programs. You have learned the basic syntax, how to use range(), how to loop through different data types, and common mistakes to watch out for.
The best way to get comfortable with for loops is to practice. Try looping through your own lists, experiment with range() parameters, and challenge yourself to solve small problems like printing a multiplication table or summing a list of numbers. The more you write, the more natural it becomes. Happy coding!