You are on page 1of 2

In Python, loops are control flow structures that allow you to execute a block of

code repeatedly. There are two main types of loops in Python: for loops and while
loops.

for Loops:
The for loop in Python is used to iterate over a sequence (such as a list, tuple,
string, or range) or other iterable objects. Here's a simple example:

python

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(fruit)
In this example, the for loop iterates through each element in the fruits list, and
the print statement is executed for each iteration.

while Loops:
The while loop in Python continues to execute a block of code as long as a
specified condition is True. Here's an example:

python

count = 0

while count < 5:


print(count)s
count += 1
In this example, the while loop continues to execute as long as the count is less
than 5. The print statement is executed in each iteration, and the count is
incremented.

Loop Control Statements:


Python also provides loop control statements that allow you to alter the flow of a
loop. The break statement is used to exit the loop prematurely, and the continue
statement is used to skip the rest of the code in the current iteration and move to
the next one.

python

for num in range(10):


if num == 5:
break # exit the loop when num is 5
print(num)
In this example, the for loop iterates over the numbers 0 to 9, and when num is
equal to 5, the break statement is encountered, causing the loop to exit.

Nested Loops:
You can also nest loops in Python, meaning one loop can be inside another. This is
useful for iterating over elements in multiple dimensions or for more complex
patterns.

python

for i in range(3):
for j in range(2):
print(f"({i}, {j})")
This nested loop prints combinations of i and j for values in the specified ranges.
Loops are essential for repetitive tasks and iterating over data structures in
Python, making them a fundamental part of the language's control flow.
Understanding how to use loops efficiently is crucial for writing effective and
concise code.

You might also like