Python Loops

Loops are essential constructs in Python that allow for executing a block of code repeatedly until a specified condition is met. Python offers two primary types of loops:

1. `for` Loop – Iterates over items of a sequence.
2. `while` Loop – Repeats as long as a specified condition is `True`.

Each of these loops has unique features and can be further controlled with keywords like `break`, `continue`, and `else`.

1. `for` Loop

The `for` loop iterates over a sequence of items (like a list, tuple, dictionary, string, or range) and executes the indented block of code for each item.
# Basic for loop
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print("Current Number:", num)

Output:
Current Number: 1
Current Number: 2
Current Number: 3
Current Number: 4
Current Number: 5


Using `for` Loop with `range()`

The `range()` function is often used with `for` loops to repeat an action a specific number of times.
# for loop with range
for i in range(1, 6):
    print("Count:", i)

Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Explanation: `range(1, 6)` generates numbers from 1 to 5, and the loop iterates over each number.

`for` Loop with Strings

The `for` loop can also be used to iterate over each character in a string.
# for loop with strings
message = "Hello"

for char in message:
    print("Character:", char)

Output:
Character: H
Character: e
Character: l
Character: l
Character: o

Explanation: The loop iterates over each character in the string `"Hello"`, printing each one.

2. `while` Loop

The `while` loop repeats as long as a specified condition remains `True`. It’s ideal for situations where the number of iterations isn’t known in advance.
# Basic while loop
count = 1

while count <= 5:
    print("Count:", count)
    count += 1

Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Explanation: The loop continues as long as `count` is less than or equal to 5, incrementing `count` by 1 in each iteration.

`break` Statement

The `break` statement exits the loop prematurely, regardless of the loop’s condition.
# Using break in a loop
for i in range(1, 10):
    if i == 5:
        print("Loop interrupted!")
        break
    print("Number:", i)

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Loop interrupted!

Explanation: The `break` statement stops the loop when `i` is 5.

`continue` Statement

The `continue` statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration.
# Using continue in a loop
for i in range(1, 6):
    if i == 3:
        print("Skipping number 3")
        continue
    print("Number:", i)

Output:
Number: 1
Number: 2
Skipping number 3
Number: 4
Number: 5

Explanation: When `i` is 3, `continue` skips the rest of the loop body and proceeds with the next iteration.

`else` Clause in Loops

In Python, `for` and `while` loops can include an `else` clause, which executes only if the loop completes without encountering a `break` statement.
# Loop with an else clause
for i in range(1, 4):
    print("Number:", i)
else:
    print("Loop completed without interruption.")

Output:
Number: 1
Number: 2
Number: 3
Loop completed without interruption.

Explanation: The `else` clause executes after the loop completes normally, without a `break`.

Nested Loops

Nested loops are loops inside other loops, useful for working with multidimensional data structures.
# Nested loop example
for i in range(1, 3):
    for j in range(1, 3):
        print("i =", i, ", j =", j)

Output:
i = 1 , j = 1
i = 1 , j = 2
i = 2 , j = 1
i = 2 , j = 2

Explanation: The outer loop (`i`) runs twice, and for each value of `i`, the inner loop (`j`) runs twice, creating a 2x2 structure.

Infinite Loops

An infinite loop keeps running until it’s explicitly stopped. Use caution with infinite loops as they can lead to unresponsive programs.
# Infinite loop (Use with caution)
while True:
    print("This is an infinite loop")
    break  # Use break to stop it

Output:
This is an infinite loop

Explanation: `while True` creates an infinite loop, but it is immediately stopped by the `break` statement.

Summary

Python’s loop structures (`for` and `while`) allow for flexible control over repeating actions within code. By using loop control statements (`break`, `continue`, and `else`), complex conditions, and nested loops, you can handle a wide range of programming tasks efficiently.

Previous: Python range and xrange | Next: String Operations

<
>