In programming, many tasks require the same set of instructions to be executed repeatedly. For example, printing numbers from 1 to 10, displaying each item in a list, calculating the sum of numbers, or processing every character in a string. Writing the same code multiple times is inefficient, difficult to maintain, and increases the chances of errors.
To solve this problem, programming languages provide loops. A loop repeatedly executes a block of code until a specified condition is met or until all items in a sequence have been processed.
Python provides two main types of loops:
True.Among these, the for loop is one of the most frequently used looping statements in Python because it is simple, readable, and ideal for working with collections of data.
In this lesson, you will learn how the Python for loop works, how to iterate through different sequences, and how to write efficient looping programs.
After completing this lesson, you will be able to:
for loop.for loop programs.for loop.for loop and a while loop.A loop is a programming structure that repeatedly executes a block of code.
Instead of writing the same statement many times, you write it once inside a loop. The loop automatically repeats the code until all required iterations are completed.
For example, suppose you want to display the numbers from 1 to 5.
Without a Loop
print(1)
print(2)
print(3)
print(4)
print(5)
This approach works for a few numbers, but it becomes impractical when the sequence contains hundreds or thousands of values.
Using a Loop
for number in range(1, 6):
print(number)
Output
1
2
3
4
5
The loop performs the repetitive work automatically with much less code.
Loops simplify repetitive programming tasks and improve code quality.
Some common situations where loops are useful include:
Without loops, these tasks would require large amounts of repetitive code.
for Loop?The Python for loop is used to iterate over a sequence. During each iteration, the loop assigns one item from the sequence to a variable and executes the statements inside the loop body.
A sequence can be:
range() objectThe loop continues until every item in the sequence has been processed.
Unlike some other programming languages, Python’s for loop does not require an initialization statement, a condition, or an increment expression. It automatically moves from one item to the next.
for Loopfor variable in sequence:
statements
The syntax consists of the following parts:
for – The keyword that starts the loop.variable – Stores the current item during each iteration.in – Indicates that the loop is iterating through a sequence.sequence – The collection of items to iterate over.statements – The code executed during each iteration.The loop ends automatically after the last item in the sequence has been processed.
for Loop WorksThe execution of a for loop follows these steps:
No manual increment is required because Python handles the iteration automatically.
for Loop ProgramLet’s write a simple program that prints five numbers.
for number in range(1, 6):
print(number)
Output
1
2
3
4
5
In this example:
range(1, 6) generates the numbers 1 through 5.number.print() statement executes once for every number.Strings are sequences of characters, so they can be processed using a for loop.
word = "Python"
for letter in word:
print(letter)
Output
P
y
t
h
o
n
During each iteration, the loop variable letter stores one character from the string.
language = "Programming"
for character in language:
print(character)
Output
P
r
o
g
r
a
m
m
i
n
g
This demonstrates that the for loop processes every character in the string automatically.
Consider the following program.
colors = ["Red", "Green", "Blue"]
for color in colors:
print(color)
print("Loop Completed")
Execution Steps
colors.Red) is assigned to color.print(color) executes.Green) is assigned to color.Blue) is assigned to color.Output
Red
Green
Blue
Loop Completed
for Loop and the while Loop| for Loop | while Loop |
|---|---|
| Iterates over a sequence. | Repeats while a condition is true. |
| Automatically moves to the next item. | Requires manual updates to the condition. |
| Best for known numbers of iterations. | Best when the number of iterations is unknown. |
| Less likely to create infinite loops. | Can create infinite loops if the condition never changes. |
In this section, you learned what loops are, why they are important, and how the Python for loop simplifies repetitive programming tasks. You explored the syntax of the for loop, understood its execution flow, and wrote your first programs using the range() function and strings. You also compared the for loop with the while loop to understand when each is most appropriate. In the next section, you will learn how to use the range() function in detail, iterate through lists, tuples, dictionaries, and sets, use the enumerate() function, create nested for loops, and avoid common beginner mistakes.
In the previous section, you learned the basics of the Python for loop and how it can iterate through strings and simple sequences. In this section, you will explore the range() function in detail and learn how to iterate through lists, tuples, dictionaries, sets, and other collections. You will also learn about the enumerate() function, nested for loops, and common mistakes that beginners often make.
range() FunctionThe range() function is one of the most common tools used with the Python for loop. It generates a sequence of numbers, making it easy to repeat a task a specific number of times.
range(stop)
range(start, stop)
range(start, stop, step)
The function can be used in three different ways:
range(stop) – Starts from 0 and stops before the specified number.range(start, stop) – Starts from the specified value and stops before the ending value.range(start, stop, step) – Starts from the specified value and increases (or decreases) by the given step.range(stop)for number in range(5):
print(number)
Output
0
1
2
3
4
The value 5 is not included because the ending value of range() is always excluded.
range(start, stop)for number in range(3, 8):
print(number)
Output
3
4
5
6
7
range(start, stop, step)for number in range(2, 11, 2):
print(number)
Output
2
4
6
8
10
The step value determines how much the sequence increases after each iteration.
for number in range(10, 0, -2):
print(number)
Output
10
8
6
4
2
A negative step allows the loop to count backwards.
Lists are one of the most commonly used data structures in Python, and the for loop is the easiest way to access each item.
fruits = ["Apple", "Banana", "Mango", "Orange"]
for fruit in fruits:
print(fruit)
Output
Apple
Banana
Mango
Orange
Each list element is assigned to the variable fruit during every iteration.
Tuples are ordered collections similar to lists, but their values cannot be changed after creation.
colors = ("Red", "Green", "Blue")
for color in colors:
print(color)
Output
Red
Green
Blue
A set is an unordered collection of unique values. A for loop can iterate through every item in a set.
numbers = {10, 20, 30, 40}
for number in numbers:
print(number)
Possible Output
10
20
30
40
The order of items may vary because sets do not preserve insertion order in all situations.
Dictionaries store data as key-value pairs. By default, a for loop iterates through the keys.
student = {
"Name": "Rahul",
"Age": 20,
"Course": "Python"
}
for key in student:
print(key)
Output
Name
Age
Course
student = {
"Name": "Rahul",
"Age": 20,
"Course": "Python"
}
for key in student:
print(key, ":", student[key])
Output
Name : Rahul
Age : 20
Course : Python
enumerate() FunctionThe enumerate() function returns both the index and the value during each iteration.
fruits = ["Apple", "Banana", "Mango"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output
0 Apple
1 Banana
2 Mango
This is useful when you need both the position and the value of each item.
for LoopsA nested for loop is a for loop placed inside another for loop.
The inner loop executes completely for every iteration of the outer loop.
for i in range(1, 4):
for j in range(1, 3):
print(i, j)
Output
1 1
1 2
2 1
2 2
3 1
3 2
Nested loops are commonly used for creating patterns, processing tables, and working with two-dimensional data.
Consider the following program.
languages = ["Python", "Java", "C++"]
for language in languages:
print(language)
print("Loop Finished")
Execution Steps
languages.Python) is assigned to language.print() statement executes.Java.C++.Output
Python
Java
C++
Loop Finished
for number in range(5)
print(number)
This causes a SyntaxError.
for number in range(5):
print(number)
This produces an IndentationError.
for number in range(1, 5):
print(number)
Output
1
2
3
4
The value 5 is excluded from the sequence.
Changing the size of a collection while looping through it can produce unexpected results. It is generally better to create a new collection or modify the data after the loop has finished.
In this section, you learned how to use the range() function in its different forms, iterate through lists, tuples, sets, and dictionaries, and use the enumerate() function to access both indexes and values. You also explored nested for loops, followed the execution flow of a loop step by step, and reviewed common beginner mistakes such as incorrect indentation, forgetting the colon, misunderstanding the range() function, and modifying collections during iteration. In the next section, you will apply these concepts by building practical programs such as multiplication tables, factorial calculators, star patterns, summing numbers, counting even and odd numbers, and processing student marks.
The Python for loop is one of the most useful programming tools because it allows repetitive tasks to be completed efficiently. Instead of writing the same statements again and again, you can use a loop to process numbers, collections, and sequences automatically.
In this section, you will build practical programs using the Python for loop. These examples will help you understand how loops are applied in real-world programming and strengthen your problem-solving skills.
for LoopThe following program displays the multiplication table of a given number.
number = 5
for i in range(1, 11):
print(number, "x", i, "=", number * i)
Output
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
The loop repeats ten times and calculates each multiplication automatically.
This program calculates the sum of the numbers from 1 to 10.
total = 0
for number in range(1, 11):
total += number
print("Sum =", total)
Output
Sum = 55
The variable total stores the running sum during each iteration.
The factorial of a positive integer is the product of all positive integers from 1 to that number.
For example:
5! = 5 × 4 × 3 × 2 × 1 = 120
number = 5
factorial = 1
for i in range(1, number + 1):
factorial *= i
print("Factorial =", factorial)
Output
Factorial = 120
Nested for loops are commonly used to create patterns.
for i in range(1, 6):
for j in range(i):
print("*", end="")
print()
Output
*
**
***
****
*****
The outer loop controls the number of rows, while the inner loop controls the number of stars printed in each row.
This program counts how many even and odd numbers exist between 1 and 10.
even_count = 0
odd_count = 0
for number in range(1, 11):
if number % 2 == 0:
even_count += 1
else:
odd_count += 1
print("Even Numbers:", even_count)
print("Odd Numbers:", odd_count)
Output
Even Numbers: 5
Odd Numbers: 5
A for loop can process every item stored in a list.
marks = [85, 92, 76, 88, 95]
for mark in marks:
print(mark)
Output
85
92
76
88
95
The loop prints each mark one after another.
This program finds the largest number in a list.
numbers = [25, 48, 16, 92, 37]
largest = numbers[0]
for number in numbers:
if number > largest:
largest = number
print("Largest Number:", largest)
Output
Largest Number: 92
The loop compares every number with the current largest value.
The following program counts the number of characters in a string.
text = "Python"
count = 0
for character in text:
count += 1
print("Total Characters:", count)
Output
Total Characters: 6
Consider the following program.
animals = ["Dog", "Cat", "Rabbit"]
for animal in animals:
print("Animal:", animal)
print("Loop Finished")
Execution Steps
animals.Dog) is assigned to animal.print() statement executes.Cat.Rabbit.Output
Animal: Dog
Animal: Cat
Animal: Rabbit
Loop Finished
for LoopsChoose descriptive names that clearly indicate the purpose of the variable.
for student in students:
print(student)
This is more readable than using names such as x or i when they do not describe the data.
Nested loops increase the number of iterations. Use them only when they are required.
Each iteration should perform one clear task. If the loop becomes very large, consider moving some code into a separate function.
range() for Numeric IterationWhen repeating a task a fixed number of times, the range() function is usually the best choice.
Instead of accessing elements by index, iterate directly over the collection.
for fruit in fruits:
print(fruit)
This approach is cleaner and easier to understand.
:) after the for statement.range() to be included.range().for number in range(1, 6)
print(number)
This produces a SyntaxError because the colon is missing.
for number in range(1, 6):
print(number)
In this section, you applied the Python for loop to practical programming problems such as generating multiplication tables, calculating sums and factorials, creating star patterns, counting even and odd numbers, processing student marks, finding the largest value in a list, and counting characters in a string. You also explored loop execution step by step, learned coding best practices, and reviewed common beginner mistakes. In the final section, you will review the complete lesson through a summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on the Python while Loop.
The Python for loop is one of the most useful programming tools because it allows repetitive tasks to be completed efficiently. Instead of writing the same statements again and again, you can use a loop to process numbers, collections, and sequences automatically.
In this section, you will build practical programs using the Python for loop. These examples will help you understand how loops are applied in real-world programming and strengthen your problem-solving skills.
for LoopThe following program displays the multiplication table of a given number.
number = 5
for i in range(1, 11):
print(number, "x", i, "=", number * i)
Output
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
The loop repeats ten times and calculates each multiplication automatically.
This program calculates the sum of the numbers from 1 to 10.
total = 0
for number in range(1, 11):
total += number
print("Sum =", total)
Output
Sum = 55
The variable total stores the running sum during each iteration.
The factorial of a positive integer is the product of all positive integers from 1 to that number.
For example:
5! = 5 × 4 × 3 × 2 × 1 = 120
number = 5
factorial = 1
for i in range(1, number + 1):
factorial *= i
print("Factorial =", factorial)
Output
Factorial = 120
Nested for loops are commonly used to create patterns.
for i in range(1, 6):
for j in range(i):
print("*", end="")
print()
Output
*
**
***
****
*****
The outer loop controls the number of rows, while the inner loop controls the number of stars printed in each row.
This program counts how many even and odd numbers exist between 1 and 10.
even_count = 0
odd_count = 0
for number in range(1, 11):
if number % 2 == 0:
even_count += 1
else:
odd_count += 1
print("Even Numbers:", even_count)
print("Odd Numbers:", odd_count)
Output
Even Numbers: 5
Odd Numbers: 5
A for loop can process every item stored in a list.
marks = [85, 92, 76, 88, 95]
for mark in marks:
print(mark)
Output
85
92
76
88
95
The loop prints each mark one after another.
This program finds the largest number in a list.
numbers = [25, 48, 16, 92, 37]
largest = numbers[0]
for number in numbers:
if number > largest:
largest = number
print("Largest Number:", largest)
Output
Largest Number: 92
The loop compares every number with the current largest value.
The following program counts the number of characters in a string.
text = "Python"
count = 0
for character in text:
count += 1
print("Total Characters:", count)
Output
Total Characters: 6
Consider the following program.
animals = ["Dog", "Cat", "Rabbit"]
for animal in animals:
print("Animal:", animal)
print("Loop Finished")
Execution Steps
animals.Dog) is assigned to animal.print() statement executes.Cat.Rabbit.Output
Animal: Dog
Animal: Cat
Animal: Rabbit
Loop Finished
for LoopsChoose descriptive names that clearly indicate the purpose of the variable.
for student in students:
print(student)
This is more readable than using names such as x or i when they do not describe the data.
Nested loops increase the number of iterations. Use them only when they are required.
Each iteration should perform one clear task. If the loop becomes very large, consider moving some code into a separate function.
range() for Numeric IterationWhen repeating a task a fixed number of times, the range() function is usually the best choice.
Instead of accessing elements by index, iterate directly over the collection.
for fruit in fruits:
print(fruit)
This approach is cleaner and easier to understand.
:) after the for statement.range() to be included.range().for number in range(1, 6)
print(number)
This produces a SyntaxError because the colon is missing.
for number in range(1, 6):
print(number)
In this section, you applied the Python for loop to practical programming problems such as generating multiplication tables, calculating sums and factorials, creating star patterns, counting even and odd numbers, processing student marks, finding the largest value in a list, and counting characters in a string. You also explored loop execution step by step, learned coding best practices, and reviewed common beginner mistakes. In the final section, you will review the complete lesson through a summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on the Python while Loop.
“`html id=”python-for-loop-chunk4″
In this lesson, you learned how the Python for loop allows a program to execute the same block of code repeatedly while iterating through a sequence of values. The for loop is one of the most commonly used looping statements in Python because it provides a simple and readable way to process strings, lists, tuples, sets, dictionaries, and numeric ranges.
You explored the syntax of the for loop, learned how the range() function works, and discovered how Python automatically moves from one item in a sequence to the next without requiring manual updates. You also practiced iterating through different data structures, used the enumerate() function to access indexes and values, and created nested for loops.
Through practical programs such as multiplication tables, factorial calculators, sum calculators, star pattern generators, even and odd number counters, and list processing examples, you learned how the for loop simplifies repetitive programming tasks.
The Python for loop is an essential building block for almost every Python program and forms the foundation for working with collections, files, and many advanced programming concepts.
for loop is used to iterate through sequences.range() function generates sequences of numbers.range(stop), range(start, stop), and range(start, stop, step) provide flexible iteration.for loop can iterate through strings, lists, tuples, sets, and dictionaries.enumerate() function returns both the index and the value.for loops are useful for patterns, tables, and two-dimensional data.for loop?A Python for loop repeatedly executes a block of code for every item in a sequence.
for loop iterate through?A for loop can iterate through strings, lists, tuples, sets, dictionaries, and range() objects.
range() function?The range() function generates a sequence of numbers for iteration.
range(5) include the number 5?No. The ending value of range() is always excluded. range(5) generates the numbers 0 through 4.
for loop and a while loop?A for loop iterates through a sequence, while a while loop continues executing as long as a specified condition remains true.
enumerate() function?The enumerate() function returns both the index and the corresponding value during each iteration.
for loop be placed inside another for loop?Yes. This is called a nested for loop and is commonly used for tables, matrices, and pattern printing.
for loop?Indentation defines the statements that belong to the loop. Incorrect indentation results in an IndentationError.
for loop.for loop.for loop that prints a square star pattern.for loop?for loop differ from a while loop?range() function?range(stop), range(start, stop), and range(start, stop, step).for loop iterate through dictionaries?enumerate() function?for loop?for loop.Create a Python program that analyzes student marks using a for loop.
Your program should:
for loop to display every mark.Student Marks:
85
92
76
88
95
Total Marks: 436
Average Marks: 87.2
Highest Mark: 95
Lowest Mark: 76
Congratulations! You have learned how to use the Python for loop to automate repetitive tasks, iterate through different collections, generate number sequences, and solve practical programming problems. The for loop is one of the most important tools in Python and will be used throughout your programming journey.
In the next lesson, you will learn the Python while Loop. You will discover how a while loop differs from a for loop, how condition-based looping works, how to avoid infinite loops, and how to create interactive programs that continue running until a specified condition becomes false.
“`