Types of Loops in Python
In Python, loops are fundamental control structures that allow a program to execute a block of code repeatedly. They are commonly used for tasks like processing lists, iterating through data, or performing repeated calculations. Python mainly provides two primary types of loops.
1. For Loop
The for loop is used to iterate over a sequence such as a list, tuple, string, or a range of numbers. It is typically used when the number of iterations is known.
Syntax
for variable in sequence:
# code block
Example
for i in range(5):
print(i)
Output
0
1
2
3
4
Explanation
-
range(5)generates numbers from 0 to 4. -
The loop runs once for each value in the sequence.
2. While Loop
The while loop repeatedly executes a block of code as long as a condition remains true. It is commonly used when the number of iterations is not predetermined.
Syntax
while condition:
# code block
Example
i = 1
while i <= 5:
print(i)
i += 1
Output
1
2
3
4
5
Explanation
-
The loop continues executing until the condition becomes false.
Loop Control Statements
Python also provides control statements that modify loop behavior.
| Statement | Description |
|---|---|
break | Terminates the loop immediately |
continue | Skips the current iteration and moves to the next |
pass | Acts as a placeholder without executing any action |
Example
for i in range(5):
if i == 3:
break
print(i)
Output
0
1
2
Conclusion
Loops are essential in Python programming because they help automate repetitive tasks and make programs more efficient. The for loop is best suited for iterating over sequences, while the while loop is ideal for condition-based repetition. By combining loops with control statements, developers can build powerful and flexible programs.
Comments
Post a Comment