fbpx

Looping Constructs in Python

Looping constructs in Python allow you to execute a block of code repeatedly. Python provides two primary types of loops: for and while. These loops enable you to iterate over sequences, perform tasks multiple times, and control the flow of your program efficiently.

The for Loop:

The for loop is 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.

Iterating over a List:

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

for fruit in fruits:
    print(fruit)

This loop prints each fruit in the fruits list.

Iterating over a Range:

for i in range(5):
    print(i)

This loop prints numbers from 0 to 4.

Using enumerate for Index and Value:

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

for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Fruit: {fruit}")

This loop prints both the index and the corresponding fruit in the list.

The while Loop:

The while loop is used to repeatedly execute a block of code as long as a specified condition is True.

count = 0

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

This loop prints numbers from 0 to 4 using a while loop.

Loop Control Statements:

break Statement:

The break statement is used to exit a loop prematurely based on a certain condition.

for i in range(10):
    if i == 5:
        break
    print(i)

This loop prints numbers from 0 to 4 and exits when i becomes 5.

continue Statement:

The continue statement is used to skip the rest of the code inside a loop for the current iteration.

for i in range(5):
    if i == 2:
        continue
    print(i)

This loop prints numbers from 0 to 4, skipping the iteration when i is 2.

else Clause with Loops:

Python allows an else clause in loops. The else block is executed when the loop condition becomes False.

for i in range(5):
    print(i)
else:
    print("Loop completed!")

In this example, “Loop completed!” is printed after the loop finishes iterating.

Looping constructs in Python are powerful tools for automating repetitive tasks, iterating over data structures, and controlling program flow based on specific conditions. Understanding how to use for and while loops, along with loop control statements, is essential for efficient and expressive Python programming.