fbpx

Loops in Python: for and while

Loops are essential constructs in programming that allow you to execute a block of code repeatedly. Python provides two primary types of loops: the for loop and the while loop.

1. The for Loop:

The for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects.

1.1 Iterating Over a List:

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

for fruit in fruits:
    print(fruit)

1.2 Iterating Over a Range:

# Example of a for loop iterating over a range
for i in range(5):
    print(i)

1.3 Iterating Over a String:

# Example of a for loop iterating over a string
word = "Python"

for letter in word:
    print(letter)

2. The while Loop:

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

# Example of a while loop
counter = 0

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

2.1 break and continue Statements:

The break statement is used to exit the loop prematurely, and the continue statement is used to skip the rest of the code in the current iteration and move to the next.

# Example of break and continue in a while loop
i = 0

while i < 10:
    i += 1

    if i == 5:
        continue  # Skip the rest of the code in this iteration

    print(i)

    if i == 8:
        break  # Exit the loop when i is 8

3. Looping with else Clause:

Both for and while loops in Python can have an else clause. The code in the else block is executed after the loop finishes its iterations, but only if the loop completed without encountering a break statement.

# Example of a for loop with an else clause
fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print(fruit)
else:
    print("Loop finished without a break statement.")

4. Nested Loops:

Loops can be nested inside each other to handle more complex scenarios.

# Example of nested loops
for i in range(3):
    for j in range(2):
        print(f"({i}, {j})")

5. Conclusion:

Loops are powerful constructs that allow you to automate repetitive tasks and process data efficiently. Whether you’re iterating over a collection, performing a specific action until a condition is met, or handling complex nested scenarios, Python’s for and while loops provide the flexibility to control the flow of your program effectively.

In the next sections, we’ll explore more advanced topics and practical applications of control flow in Python.