2. Loops

Loops allow us to repeat a block of code multiple times. There are two main types of loops in Python: for loops and while loops.

For Loop:

A for loop is used when you know how many times you want to execute a block of code. It iterates over a sequence (like a list, range, string, or tuple).

Syntax:

for variable in sequence:
    # code to be executed

Example 1: Iterating over a Range

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

Explanation: range(5) generates the numbers 0, 1, 2, 3, 4. The for loop prints each of these.

Output:

0
1
2
3
4

Example 2: Iterating over a List

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Explanation: The loop goes through each item in the fruits list and prints it.

Output:

apple
banana
cherry

While Loop:

A while loop runs as long as the condition is True. It is useful when you don’t know in advance how many times to repeat the block.

Syntax:

while condition:
    # code to be executed

Example 1: Basic While Loop

i = 0
while i < 5:
    print(i)
    i += 1

Explanation: The loop starts with i = 0 and runs until i is less than 5. After each iteration, i is incremented by 1.

Output:

0
1
2
3
4

Example 2: While Loop with Break

i = 0
while i < 5:
    if i == 3:
        break
    print(i)
    i += 1

Explanation: The loop runs until i equals 3. At that point, the break statement stops the loop.

Output:

0
1
2