Python Loops Basics
Loops are one of the most powerful concepts in any programming language.
They allow you to repeat a block of code multiple times β saving effort, avoiding repetition, and making your programs more efficient.
In this guide, youβll learn everything about Python loops, including:
forloopwhileloopbreak,continue, andpassstatements- Loop
elseblocks - Common examples and use cases
Letβs dive in! π
π§ What is a Loop?
A loop allows you to execute a block of code repeatedly until a certain condition is met.
There are mainly two types of loops in Python:
- for loop β Used for iterating over a sequence (like list, tuple, dictionary, string, or range).
- while loop β Used for repeating a block of code as long as a condition is
True.
πΉ 1. for Loop
The for loop is used when you want to iterate over a sequence (like a list, tuple, or string) and perform actions for each element.
π§© Syntax:
for variable in sequence:
# Code block
β Example 1: Looping through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
β Example 2: Looping through a string
for char in "Python":
print(char)
Output:
P
y
t
h
o
n
β
Example 3: Using range() in loops
The range() function generates a sequence of numbers.
for i in range(5):
print(i)
Output:
0
1
2
3
4
π By default, range(start, stop, step) starts at 0 and stops before the given number.
Example with step:
for i in range(2, 10, 2):
print(i)
Output:
2
4
6
8
β
Example 4: Looping through a list using range()
Sometimes, you may want to use indexes while looping through a list β for example, when you need both the index and the value.
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
π‘ Tip:
You can also use the built-in enumerate() function for cleaner index-based looping:
for i, fruit in enumerate(fruits):
print(i, fruit)
β Example 5: Looping through a dictionary
When looping through dictionaries, you can iterate over:
- Keys
- Values
- Key-value pairs
person = {"name": "Alice", "age": 25, "city": "Mumbai"}
# Loop through keys
for key in person:
print(key)
# Loop through values
for value in person.values():
print(value)
# Loop through key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
Output:
name
age
city
Alice
25
Mumbai
name: Alice
age: 25
city: Mumbai
πΉ 2. while Loop
A while loop executes a block of code as long as the condition is True.
π§© Syntax:
while condition:
# Code block
β Example: Counting numbers
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
β οΈ If the condition never becomes False, the loop runs forever (infinite loop).
πΈ 3. Loop Control Statements
Python provides three special statements to control the flow of loops:
β€ break
Stops the loop entirely when a certain condition is met.
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
β€ continue
Skips the current iteration and moves to the next one.
for i in range(6):
if i == 3:
continue
print(i)
Output:
0
1
2
4
5
β€ pass
Used as a placeholder when you donβt want to execute any code yet.
for i in range(5):
pass # Placeholder for future code
πΈ 4. Loop else Block
An else block can be added to loops in Python.
The else part runs after the loop finishes normally (not when stopped by break).
β Example:
for i in range(5):
print(i)
else:
print("Loop completed successfully!")
Output:
0
1
2
3
4
Loop completed successfully!
πΉ 5. Nested Loops
You can place one loop inside another loop β useful for working with multi-dimensional data like matrices or nested lists.
for i in range(1, 4):
for j in range(1, 4):
print(f"({i}, {j})", end=" ")
print()
Output:
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
π§° 6. Common Loop Use Cases
| Use Case | Example |
|---|---|
| Print numbers 1β10 | for i in range(1, 11): print(i) |
| Sum of numbers | sum = 0; for i in range(1,6): sum += i |
| Loop through dictionary | for k,v in dict.items(): print(k,v) |
| Search element in list | for item in list: if item==target: break |
| Filter even numbers | [x for x in range(10) if x%2==0] |
π Bonus: List Comprehensions (Short Loops in One Line)
Python allows loops in a single line to create lists concisely.
squares = [x**2 for x in range(5)]
print(squares)
Output:
[0, 1, 4, 9, 16]
π§© Summary Table
| Type | Syntax | Use Case |
|---|---|---|
| for loop | for i in sequence: | Iterate over sequences (lists, strings, etc.) |
| while loop | while condition: | Repeat until condition becomes False |
| break | β | Stop loop early |
| continue | β | Skip current iteration |
| pass | β | Placeholder (does nothing) |
| else | for/while ... else: | Runs when loop finishes normally |
π‘ Final Thoughts
Loops are the core building blocks of Python programming.
They make your code more efficient and dynamic by avoiding repetition.
Remember:
- Use
forloops for iterating over collections. - Use
whileloops for condition-based repetition. - Use
break,continue, andpassto control loop flow.