Python Loops
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices for running the loops. The basic functionality of all the techniques is the same, although the syntax and the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.
There are two primary types of loops in Python:
forloopwhileloop
1. for Loop
In Python, the for loop iterates over a sequence: like a list or tuple or string or range. It executes a block of code for each item in the sequence.
Syntax:
for variable in sequence:
# Code block to execute
Examples:
- Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
2. Using range:
for i in range(5):
print(i)
Output:
0
1
2
3
4
3. Iterating over a string:
for char in "hello":
print(char)
Output:
h
e
l
l
o
4. With else: The else block runs after the for loop finishes unless the loop is terminated with a break.
for i in range(3):
print(i)
else:
print("Loop finished")
Output:
0
1
2
Loop finished
2. while loop
It performs as long as a given condition is True. It is applied when the number of iterations is not known beforehand.
Syntax:
while condition:
# Code block to execute
Examples:
- Basic Example
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
2. With break: The break statement immediately exits the loop.
count = 0
while True:
print(count)
count += 1
if count == 3:
break
Output:
0
1
2
3. With else: Like the for loop, the else block executes unless the loop is terminated with a break.
count = 0
while count < 3:
print(count)
count += 1
else:
print("Finished")
Output:
0
1
2
Finished
Special Control Statements
break: Exits the loop entirely.
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2
2. continue: skips the current iteration and continues to the next one.
for i in range(5):
if i == 3:
continue
print(i)
Output:
0
1
2
4
3. pass: Does nothing; used as a placeholder.
for i in range(5):
if i == 3:
pass
print(i)
Output:
0
1
2
3
4
Key Points to Remember
- The
forloop is typically used when you know the number of iterations or are iterating over a sequence. - A
whileloop is used when the number of iterations depends on some condition. - Use
breakto exit the loop early andcontinueto skip an iteration. - Use
elsefor clean-up or further steps when a loop naturally ends.