Looping technique in Python
In Python, looping is a basic concept that allows a block of code to be executed repeatedly. Python has several ways of looping through a block of code, which include for loops, while loops, and more advanced iteration techniques using built-in functions and comprehensions. Let’s go over everything in detail.
1. Types of Loops in Python
Python supports two main types of loops:
- for loop – This iterates over a sequence, such as lists, tuples, strings, dictionaries, ranges, etc.
- while loop – Loops through as long as a condition is
True.
1.1 for Loop
The for loop is used to iterate over sequences such as lists, tuples, dictionaries, strings, and ranges.
Syntax:
for variable in sequence:
# Loop body
Example: Iterating through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example: Using range()
for i in range(5): # range(5) generates numbers from 0 to 4
print(i)
Output:
0
1
2
3
4
Example: Iterating through a string
word = "Python"
for letter in word:
print(letter)
Output:
P
y
t
h
o
n
Example: Iterating through a dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
for key, value in person.items():
print(f"{key}: {value}")
Output:
name: Alice
age: 25
city: New York
1.2 while Loop
A while loop runs as long as a specified condition remains True.
Syntax:
while condition:
# Loop body
Example: Counting with while loop
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
Example: Infinite loop (use with caution)
while True:
print("This will run forever!")
break # Stops the infinite loop
2. Controlling Loops
Python provides special statements to control loops:
2.1 break Statement
Stops the loop immediately.
for num in range(10):
if num == 5:
break # Stops at 5
print(num)
Output:
0
1
2
3
4
2.2 continue Statement
Skips the rest of the loop body and moves to the next iteration.
for num in range(5):
if num == 2:
continue # Skips 2
print(num)
Output:
0
1
3
4
2.3 pass Statement
Does nothing; acts as a placeholder.
for num in range(3):
if num == 1:
pass # Placeholder
print(num)
Output:
0
1
2
3. Looping with else Clause
Python allows an else block to run when the loop finishes normally.
Example with for loop
for num in range(3):
print(num)
else:
print("Loop finished successfully!")
Output:
0
1
2
Loop finished successfully!
Example with while loop
count = 0
while count < 3:
print(count)
count += 1
else:
print("While loop completed")
Output:
0
1
2
While loop completed
Using break with else
If a loop is terminated using break, the else block won’t execute.
for num in range(5):
if num == 3:
break
print(num)
else:
print("Loop completed") # This won't execute
Output:
0
1
2
4. Nested Loops
Loops can be nested within other loops.
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
5. Advanced Looping Techniques
5.1 List Comprehension (for loop in a single line)
squares = [x**2 for x in range(5)]
print(squares)
Output:
[0, 1, 4, 9, 16]
5.2 Dictionary Comprehension
num_square = {x: x**2 for x in range(3)}
print(num_square)
Output:
{0: 0, 1: 1, 2: 4}
5.3 Looping with enumerate()
enumerate() helps track index positions while iterating.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
Output:
0: apple
1: banana
2: cherry
5.4 Looping with zip()
zip() pairs elements from multiple sequences.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
Output:
Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.
6. Asynchronous Loops (asyncio)
Python supports asynchronous loops for non-blocking execution.
import asyncio
async def print_numbers():
for i in range(3):
print(i)
await asyncio.sleep(1) # Simulate a delay
asyncio.run(print_numbers())
Output (with 1-second pauses):
0
1
2
Conclusion
- Use
forloops when iterating over sequences. - Use
whileloops when the number of iterations is unknown. - Use
break,continue, andpassto control loop behavior. - Use comprehensions (
list,dict) for concise looping. - Use
enumerate()andzip()for structured iteration. - Use
asyncloops (await asyncio.sleep()) for non-blocking operations.