Loops in Python

Loops in Python

In Python, loops are control structures that allow you to repeatedly execute a block of code based on a certain condition.

Types of loops

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

1. 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.

# Example of a for loop
fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print(f"Current fruit: {fruit}")

Output:

Current fruit: apple
Current fruit: banana
Current fruit: orange

2. while Loop:

The while loop repeatedly executes a block of code as long as a specified condition is true.

# Example of a while loop
counter = 0

while counter < 5:
    print(f"Current count: {counter}")
    counter += 1

Output:

Current count: 0
Current count: 1
Current count: 2
Current count: 3
Current count: 4

In this example, the while loop continues to execute as long as the condition counter < 5 is true.

Loops are essential for automating repetitive tasks, iterating over data structures, and implementing various algorithms. They provide a way to execute a set of instructions multiple times, making your code more efficient and concise.

Additional resources

You can refer to Abhishek Veeramalla's GitHub repo. Click here.

What's next?

In the next article in this blog series, we will go through Python real time use case with Lists & Exceptional Handling.

Stay tuned.