- Courses
- đ»Programming Languages
- đPython
- Control Flow
- For Loops
On this page
For Loops
What a For Loop Isâ
A for loop repeats a block of code for each item in a sequence. Instead of writing the same instruction multiple times, you instruct Python to iterate through values automatically. This mechanism is essential for processing lists, strings, ranges, and other iterable objects.
A for loop always follows the same structure:
for variable in sequence:
# repeated block
Python assigns each item in the sequence to the loop variable, one at a time, and executes the indented block for each item.
Looping Over a Listâ
Lists are one of the most common sequences used with for loops.
numbers = [10, 20, 30]
for n in numbers:
print(n)
The loop runs three times. Each time, n takes the next value from the list.
Looping Over a Stringâ
Strings are sequences of characters. A for loop can process each character individually.
text = "Python"
for ch in text:
print(ch)
This technique is useful for analyzing or transforming text.
Looping with range()â
The range() function generates a sequence of numbers. It is commonly used when you need a specific number of repetitions.
for i in range(5):
print(i)
This prints:
0
1
2
3
4
Range Variantsâ
range() supports start, stop, and step values.
for i in range(2, 10, 2):
print(i)
This prints even numbers from 2 to 8.
Using the Loop Variableâ
The loop variable is available inside the loop block and can be used in expressions.
for i in range(1, 6):
print("Square of", i, "is", i * i)
Each iteration computes a new result based on the current value of i.
Accumulating Resultsâ
For loops often build or accumulate results.
total = 0
for n in [3, 5, 7]:
total += n
print("Total:", total)
This pattern appears frequently in data processing tasks.
Nested For Loopsâ
A loop can appear inside another loop. This is useful for working with multiâdimensional data or generating combinations.
for x in range(2):
for y in range(3):
print(x, y)
Nested loops must be used carefully to maintain clarity.
Why For Loops Matterâ
For loops allow you to process sequences, repeat operations, analyze data, and build structured logic. They are essential for tasks such as iterating through lists, reading files line by line, generating patterns, and performing calculations across collections of values. Mastering for loops prepares you for more advanced controlâflow structures and dataâprocessing techniques in later modules.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Match/Case Statements
Next
While Loops
-
What a For Loop Is
-
Looping Over a List
-
Looping Over a String
-
Looping with
range()- Range Variants
-
Using the Loop Variable
-
Accumulating Results
-
Nested For Loops
-
Why For Loops Matter