Loops in Python

Rina Mondal
2 min readMar 22, 2024

--

Loops are an essential concept in programming, allowing developers to execute a block of code repeatedly. In other words, a loop is a control flow statement that iterates over a sequence of elements for a specified range or until a certain condition is met.

In this blog post, we’ll delve into the intricacies of loops in Python, exploring their types, syntax, and best practices.

Python supports two main types of loops: for loops and while loops.

Difference between For Loops and While Loops:

A for loop is typically used when you know the number of iterations you want to perform beforehand.

A while loop is used when you want to execute a block of code repeatedly as long as a specified condition is true.

For Loops: ( Everything related to For loops in Python)

For loops in Python are used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in the sequence.

#Syntax for a "for loop"
for item in sequence:
# Code block to be executed

Here’s an example of a for loop iterating over a list of numbers:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)

# O/t-
1
2
3
4
5

While Loops: ( Everything related to While loops in Python)

While loops in Python repeatedly execute a block of code as long as a specified condition is true. The syntax for a while loop is:

while condition:
# Code block to be executed

Here’s an example of a while loop that prints numbers from 1 to 5:

count = 1
while count <= 5:
print(count)
count += 1

Nested Loops:

Python allows nesting loops within one another. This means you can have a loop inside another loop. Nested loops are useful when dealing with multidimensional data structures.

Control Flow in Loops:

Python provides control flow statements such as break, continue, and else that can be used within loops to alter their behavior.

- break: Terminates the loop prematurely.
- continue: Skips the rest of the code block and proceeds to the next iteration of the loop.
- else: Executes a block of code when the loop completes without hitting a break statement.

Loops are powerful constructs in Python that allow developers to iterate over sequences and perform repetitive tasks efficiently.

--

--

Rina Mondal

I have an 8 years of experience and I always enjoyed writing articles. If you appreciate my hard work, please follow me, then only I can continue my passion.