Loops in Python
What are Loops?
A loop is a way to repeat a block of code multiple times without writing the same code again and again.
In real life we do many repetitive tasks:
- Checking attendance of 50 students one by one
- Sending the same message to 100 customers
- Adding all numbers from 1 to 100
Instead of writing the code 50 or 100 times, we write it once and tell Python to repeat it.
Python has two main types of loops:
- for loop → used when we know how many times to repeat, or when we want to go through each item in a collection
- while loop → used when we want to repeat as long as a condition is True
Both are extremely important. You will use them in almost every program, especially when working with lists, tuples, sets and dictionaries.
The for Loop
The for loop is used to iterate over a sequence (list, tuple, string, set, dictionary, or range).
Basic Syntax:
for variable in sequence:
# code to repeat
statement 1
statement 2
How it works step by step:
- Python takes the first item from the sequence and stores it in the variable
- It runs the indented block of code
- Then it takes the next item and repeats the process
- This continues until all items are finished
Example 1 – Simple for loop
for i in range(5):
print("Hello", i)
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
The loop ran 5 times. Each time the value of i changed from 0 to 4.
Example 2 – Looping through a string
name = "PYTHON"
for letter in name:
print(letter)
The range() Function
range() is very commonly used with for loops.
It generates a sequence of numbers.
Three ways to use range():
# 1. range(stop) → from 0 to stop-1
for i in range(5):
print(i)
# Output: 0 1 2 3 4
# 2. range(start, stop) → from start to stop-1
for i in range(2, 7):
print(i)
# Output: 2 3 4 5 6
# 3. range(start, stop, step)
for i in range(1, 10, 2):
print(i)
# Output: 1 3 5 7 9
# Negative step (counting backwards)
for i in range(10, 0, -2):
print(i)
# Output: 10 8 6 4 2
The while Loop
The while loop repeats a block of code as long as a condition remains True.
Syntax:
while condition:
# code to repeat
statement 1
statement 2
How it works:
- Python checks the condition
- If True → runs the block
- Goes back and checks the condition again
- Continues until the condition becomes False
Example 1 – Counting
count = 1
while count <= 5:
print("Count is:", count)
count = count + 1
print("Loop finished")
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Loop finished
When count becomes 6, the condition
count <= 5 becomes False and the loop stops.
Example 2 – Taking input until user stops
total = 0
while True:
num = int(input("Enter a number (0 to stop): "))
if num == 0:
break
total = total + num
print("Total =", total)
Warning – Infinite Loop
# Dangerous example (never run this without break)
count = 1
while count <= 5:
print(count)
# forgot to increase count → infinite loop
When to use for and when to use while?
Use for loop when:
- You know how many times you want to repeat
- You want to go through each item of a list, tuple, set or dictionary
- You are using range()
Use while loop when:
- You don’t know in advance how many times the loop will run
- You want to repeat until a certain condition becomes False
- You are waiting for user input or some external condition
Same task done with both loops:
# Using for
print("Using for loop:")
for i in range(1, 6):
print(i)
# Using while
print("Using while loop:")
i = 1
while i <= 5:
print(i)
i = i + 1
Looping through Lists
Lists are the most common data type used with loops.
Method 1 – Direct iteration (most common)
fruits = ["apple", "banana", "mango", "orange"]
for fruit in fruits:
print(fruit)
Method 2 – Using index
fruits = ["apple", "banana", "mango", "orange"]
for i in range(len(fruits)):
print("Index:", i, "Value:", fruits[i])
Method 3 – while loop with list
fruits = ["apple", "banana", "mango", "orange"]
i = 0
while i < len(fruits):
print(fruits[i])
i = i + 1
Practical Example – Calculating total and average
marks = [78, 85, 92, 67, 88]
total = 0
for m in marks:
total = total + m
average = total / len(marks)
print("Total:", total)
print("Average:", average)
Looping through Tuples
Tuples work exactly like lists in loops. The only difference is that tuples cannot be changed.
point = (10, 20, 30)
for value in point:
print(value)
Unpacking inside loop (very useful)
students = [
("Rahul", 85),
("Priya", 92),
("Amit", 78),
("Sneha", 95)
]
for name, marks in students:
print(name, "scored", marks)
if marks >= 90:
print(" → Excellent")
Using while with tuple
colors = ("red", "green", "blue", "yellow")
i = 0
while i < len(colors):
print(colors[i])
i += 1
Looping through Sets
You can loop through a set, but remember:
- Sets are unordered → order of items is not guaranteed
- Sets do not support indexing (no set[0])
skills = {"python", "sql", "excel", "powerbi", "tableau"}
print("My skills:")
for skill in skills:
print("-", skill)
Practical Example – Checking required skills
required = {"python", "sql", "excel"}
candidate = {"python", "sql", "powerbi", "excel", "ml"}
print("Checking required skills:")
for skill in required:
if skill in candidate:
print(skill, "→ Found")
else:
print(skill, "→ Missing")
Looping through Dictionaries
Dictionaries are extremely common in data work. There are three main ways to loop through them.
1. Loop through keys only
student = {
"name": "Kundan",
"age": 22,
"course": "Data Analytics",
"marks": 87
}
for key in student:
print(key)
# Same thing
for key in student.keys():
print(key)
2. Loop through values only
for value in student.values():
print(value)
3. Loop through keys and values together (most useful)
for key, value in student.items():
print(key, "→", value)
Practical Example – Printing student details
students = [
{"name": "Rahul", "marks": 85},
{"name": "Priya", "marks": 92},
{"name": "Amit", "marks": 78}
]
for s in students:
print(s["name"], "scored", s["marks"])
if s["marks"] >= 90:
print(" Grade: A+")
elif s["marks"] >= 80:
print(" Grade: A")
else:
print(" Grade: B")
enumerate() and zip()
enumerate() gives you both index and value while looping.
fruits = ["apple", "banana", "mango"]
for index, fruit in enumerate(fruits):
print(index, fruit)
# You can also start from 1
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
zip() lets you loop through two or more lists at the same time.
names = ["Rahul", "Priya", "Amit"]
marks = [85, 92, 78]
for name, score in zip(names, marks):
print(name, "→", score)
The break Statement
break is used to exit the loop immediately, even if the condition is still True or items are remaining.
numbers = [10, 25, 30, 45, 50, 60]
for num in numbers:
if num == 45:
print("Found 45 → stopping the loop")
break
print(num)
print("Loop ended")
10
25
30
Found 45 → stopping the loop
Loop ended
When 45 is found, break is executed and the remaining numbers (50, 60) are not processed.
With while loop
count = 1
while count <= 10:
print(count)
if count == 5:
break
count += 1
The continue Statement
continue skips the current iteration and moves to the next one.
It does not stop the entire loop.
numbers = [10, 25, 30, 45, 50, 60]
for num in numbers:
if num == 30:
continue # skip this number
print(num)
10
25
45
50
60
30 was skipped because of continue.
Practical use – Skip invalid data
marks = [78, -5, 92, 0, 85, -10, 67]
print("Valid marks:")
for m in marks:
if m <= 0:
continue
print(m)
else Clause with Loops
Python allows an else block with both for and while loops.
The else block runs only when the loop finishes normally (not by break).
numbers = [2, 4, 6, 8, 10]
for num in numbers:
if num % 2 != 0:
print("Odd number found")
break
else:
print("All numbers are even")
Nested Loops
A loop inside another loop is called a nested loop.
for i in range(1, 4):
for j in range(1, 4):
print(i, "x", j, "=", i*j)
print("------")
Real Example – Printing student marks subject-wise
students = {
"Rahul": [85, 90, 78],
"Priya": [92, 88, 95],
"Amit": [70, 75, 80]
}
for name, marks in students.items():
print("Student:", name)
total = 0
for m in marks:
print(" Subject marks:", m)
total += m
print(" Total:", total)
print("------")
Real-World Examples
Example 1 – Filter customers using for loop
customers = [
{"name": "Amit", "balance": 45000, "city": "Delhi"},
{"name": "Priya", "balance": 82000, "city": "Mumbai"},
{"name": "Rahul", "balance": 15000, "city": "Delhi"},
{"name": "Sneha", "balance": 95000, "city": "Bangalore"}
]
print("Customers with balance > 50000:")
for cust in customers:
if cust["balance"] > 50000:
print(cust["name"], "→", cust["balance"])
Example 2 – Using while loop for menu
while True:
print("\n1. View Balance")
print("2. Deposit")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == "1":
print("Your balance is 25000")
elif choice == "2":
print("Deposit successful")
elif choice == "3":
print("Thank you!")
break
else:
print("Invalid choice")
Example 3 – Combining for + condition + dictionary
sales = {
"Jan": 45000,
"Feb": 52000,
"Mar": 48000,
"Apr": 61000,
"May": 39000
}
print("Months with sales above 50000:")
for month, amount in sales.items():
if amount > 50000:
print(month, "→", amount)
Loops in Python
Complete and detailed explanation of for and while loops with all data types.
Select any topic from the left sidebar to begin.
Start Learning →
