Python For Loop
A for loop is used in Python to repeat a block of code for every item in a sequence or collection.
Python For Loop
At CIIT Training Institute, loops are taught using practical programming examples so that students can understand not only the syntax but also where loops are actually used in real applications.
The for loop is one of the most commonly used looping statements in Python. It is useful when we want to process multiple values one by one.
What is a For Loop?
A for loop executes a block of code once for each item in an iterable object.
An iterable can be:
- List
- Tuple
- String
- Set
- Dictionary
- Range
Instead of writing the same code multiple times, we can use a loop.
For Loop Concept
Suppose we have three students:
students = ["Sam", "Rahul", "Priya"]
Instead of writing three separate print statements, we can use a for loop.
The loop continues until all items in the collection have been processed.
For Loop Syntax
for variable in sequence:
# code to execute
Example
students = ["Sam", "Rahul", "Priya"]
for student in students:
print(student)
Output
Sam
Rahul
Priya
The variable student receives one item at a
time from the list.
Iterating Over a List
A for loop is commonly used to process every item inside a list.
courses = [
"Python",
".NET",
"Java",
"Data Science"
]
for course in courses:
print(course)
Output
Python
.NET
Java
Data Science
Iterating Over a String
A string is also iterable. The loop processes one character at a time.
name = "SAM"
for character in name:
print(character)
Output
S
A
M
Iterating Over a Tuple
technologies = ("Python", "Django", "Flask")
for technology in technologies:
print(technology)
Each tuple element is accessed one by one.
Iterating Over a Set
skills = {"Python", "SQL", "Git"}
for skill in skills:
print(skill)
A set can also be iterated using a for loop. Remember that sets do not guarantee a meaningful element order.
For Loop With Dictionary
Dictionaries contain key-value pairs. We can iterate through keys, values, or both.
1. Iterate Through Keys
student = {
"name": "Sam",
"course": "Python",
"city": "Pune"
}
for key in student:
print(key)
2. Iterate Through Values
for value in student.values():
print(value)
3. Iterate Through Key and Value
for key, value in student.items():
print(key, ":", value)
Output
name : Sam
course : Python
city : Pune
range() With For Loop
The range() function is frequently used
when we want to repeat something a specific number
of times.
for number in range(5):
print(number)
Output
0
1
2
3
4
range() is excluded.
Therefore, range(5) generates values
from 0 to 4.
range(start, stop)
for number in range(1, 6):
print(number)
Output
1
2
3
4
5
Here, 1 is the starting value and
6 is the stopping value.
Since the stop value is excluded, the loop ends at 5.
range(start, stop, step)
The third parameter specifies how much the value should change after every iteration.
for number in range(1, 11, 2):
print(number)
Output
1
3
5
7
9
Here the loop increases the value by 2 after every iteration.
Reverse Iteration
A negative step can be used to iterate backwards.
for number in range(5, 0, -1):
print(number)
Output
5
4
3
2
1
enumerate() Function
enumerate() allows us to access both
the index and the value while looping.
courses = ["Python", ".NET", "Java"]
for index, course in enumerate(courses):
print(index, course)
Output
0 Python
1 .NET
2 Java
We can also start the index from another number.
for index, course in enumerate(courses, start=1):
print(index, course)
1 Python
2 .NET
3 Java
Nested For Loop
A loop inside another loop is called a nested loop.
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
The inner loop runs completely for every iteration of the outer loop.
Example: Multiplication Table
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 10 = 50
break Inside For Loop
The break statement immediately stops
the loop.
for number in range(1, 10):
if number == 5:
break
print(number)
Output
1
2
3
4
As soon as number == 5, the loop stops.
continue Inside For Loop
The continue statement skips the current
iteration and moves to the next iteration.
for number in range(1, 6):
if number == 3:
continue
print(number)
Output
1
2
4
5
Number 3 is skipped, but the loop continues.
else With For Loop
Python also allows an else block with
a for loop.
The else block executes when the loop
completes normally without encountering
break.
for number in range(1, 4):
print(number)
else:
print("Loop completed")
Output
1
2
3
Loop completed
Example With break
for number in range(1, 6):
if number == 3:
break
print(number)
else:
print("Loop completed")
Output:
1
2
Here the else block does not execute
because the loop was terminated using
break.
Example: CIIT Student Courses 📩🤓
Suppose CIIT has a list of courses and we want to display each course.
courses = [
"Python Full Stack",
".NET Full Stack",
"Java Full Stack",
"Data Science",
"Data Analytics"
]
for course in courses:
print("Available Course:", course)
Output
Available Course: Python Full Stack
Available Course: .NET Full Stack
Available Course: Java Full Stack
Available Course: Data Science
Available Course: Data Analytics
This is a simple example of how loops can be used to process multiple records.
Example: Calculate Sum 📩
numbers = [10, 20, 30, 40, 50]
total = 0
for number in numbers:
total = total + number
print("Total =", total)
Output
Total = 150
The loop processes every number and adds it to
total.
Example: Filter Even Numbers 🫠📩
numbers = [10, 15, 20, 25, 30, 35]
for number in numbers:
if number % 2 == 0:
print(number)
Output
10
20
30
The modulo operator % is used to check
whether a number is divisible by 2.
Common Mistakes in For Loop
| Mistake | Explanation |
|---|---|
| Incorrect indentation | Python uses indentation to identify the loop body. |
| Forgetting colon |
The for statement must end with
:.
|
| range() end value confusion | The stop value is not included. |
| Using wrong iterable | Make sure the object can be iterated. |
| Unexpected set order | Sets do not provide a meaningful guaranteed iteration order. |
Important: Loop Variable
The loop variable automatically receives the next item from the iterable.
students = ["Sam", "Rahul", "Priya"]
for student in students:
print(student)
Here student changes automatically:
- First iteration → Sam
- Second iteration → Rahul
- Third iteration → Priya
We normally should not manually modify the loop variable to control the loop.
For Loop vs While Loop
| For Loop | While Loop |
|---|---|
| Commonly used to iterate over a collection. | Commonly used when repetition depends on a condition. |
| Works naturally with lists, strings, tuples, sets and dictionaries. | Continues while a condition remains true. |
| Usually easier when the number or collection of items is known. | Useful when the number of iterations is not known in advance. |
CIIT Learning Point
Remember:
Python's for loop is mainly used to process items from
an iterable one by one. Learn range(),
enumerate(), break,
continue and nested loops properly because
these concepts are frequently used in real-world
Python applications and coding interviews.
CIIT Practice Tasks
- Create a list of 5 student names and print every student using a for loop.
-
Print numbers from 1 to 20 using
range(). - Print all even numbers between 1 and 50.
- Create a multiplication table program where the user enters a number.
-
Create a list of course names and display their
index and name using
enumerate(). - Create a list of numbers and calculate their total using a for loop.
Summary :
A Python for loop is used to iterate
through items in collections such as lists, tuples,
strings, sets and dictionaries. The
range() function is useful for controlled
repetition, while enumerate() provides both
index and value. We can use break to stop
a loop, continue to skip an iteration and
nested loops to handle multiple levels of repetition.
Understanding for loops is essential for Python
programming and real-world application development.