HomepythonMastering Loops in Python: For, While, Break, Continue, and Else

Mastering Loops in Python: For, While, Break, Continue, and Else

Mastering Loops in Python: For, While, Break, Continue, and Else

In Python, loops are essential for executing a block of code repeatedly. They are fundamental in programming for handling repetitive tasks, iterating over data structures, and more. This article will explore for and while loops, the break and continue operators, and the powerful else clause that can be used with loops.

For Loops

The for loop is used for iterating over a sequence such as a list, tuple, dictionary, set, or string. It executes a block of code for each item in the sequence.

Syntax:

for variable in sequence:
    # Code block to be executed

Example:

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

Output:

In this example, the for loop iterates over each element in the numbers list and prints it.

While Loops

The while loop in Python is used to repeatedly execute a block of code as long as a condition is True. It’s particularly useful when the number of iterations is not known beforehand.

Syntax:

while condition:
    # Code block to be executed

Example:

count = 0

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

Output:

0
1
2
3
4

Here, the while loop continues to execute the code block as long as count is less than 5. The value of count is incremented in each iteration.

Break and Continue Operators

  • break Operator: Terminates the loop prematurely when encountered.
  • continue Operator: Skips the rest of the code inside the loop for the current iteration and jumps to the next iteration.

Example with break:

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

Output:

0
1
2
3
4

In this example, the loop is terminated when number is equal to 5, so numbers from 0 to 4 are printed.

Example with continue:

for number in range(10):
    if number % 2 == 0:
        continue
    print(number)

Output:

1
3
5
7
9

Here, the continue statement skips the even numbers, so only odd numbers are printed.

Else Clause in Loops

Python allows an else clause to be used with loops. The else block is executed after the loop completes normally (i.e., not terminated by break).

Syntax with for Loop:

for variable in sequence:
    # Code block to be executed
else:
    # Code block to be executed after loop completes

Syntax with while Loop:

while condition:
    # Code block to be executed
else:
    # Code block to be executed after loop completes

Example with for Loop:

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

Output:

0
1
2
3
4
Loop completed

The else block is executed after the for loop finishes iterating over the sequence.

Example with while Loop:

count = 0

while count < 5:
    print(count)
    count += 1
else:
    print("Loop completed")

Output:

0
1
2
3
4
Loop completed

Similarly, the else block is executed after the while loop condition becomes False.

Example with break in Loop:
When the loop is terminated by break, the else block is not executed.

for number in range(5):
    if number == 3:
        break
    print(number)
else:
    print("Loop completed")

Output:

0
1
2

Here, the break statement causes the loop to terminate when number is equal to 3, so the else block is not executed.

Nested Loops

You can have loops within loops, known as nested loops. This is useful for iterating over multi-dimensional data structures.

Example:

for i in range(3):
    for j in range(3):
        print(f"i={i}, j={j}")

Output:

i=0, j=0
i=0, j=1
i=0, j=2
i=1, j=0
i=1, j=1
i=1, j=2
i=2, j=0
i=2, j=1
i=2, j=2

In this example, the outer loop runs three times, and for each iteration of the outer loop, the inner loop runs three times, printing all combinations of i and j.

Using continue in Nested Loops

Example:

for i in range(3):
    for j in range(3):
        if j == 1:
            continue
        print(f"i={i}, j={j}")

Output:

i=0, j=0
i=0, j=2
i=1, j=0
i=1, j=2
i=2, j=0
i=2, j=2

In this example, when j is equal to 1, the continue statement skips the rest of the code inside the inner loop for that iteration, so the combination i=0, j=1, i=1, j=1, and i=2, j=1 are not printed.

Combining while Loop with break and else

Example:

count = 0

while count < 5:
    if count == 3:
        break
    print(count)
    count += 1
else:
    print("Loop completed")

Output:

0
1
2

In this example, the break statement causes the loop to terminate when count is equal to 3, so the else block is not executed.

Conclusion

Understanding loops in Python is crucial for effective programming. The for and while loops provide flexibility in iterating over sequences and repeating tasks. The break and continue operators offer control over the loop’s execution, allowing you to exit or skip iterations as needed. The else clause adds a powerful feature that runs a block of code after the loop finishes normally. Mastering these constructs will significantly enhance your ability to write efficient and readable Python code.

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

Popular