How to Use the Else Block in For and While Loops in Python

In this article, we will explore the uncommon syntax of the else block in both for and while loops. Understanding this difference is important before using it in your programs. We will look at the two sample programs: one using a for loop and another using a while loop.

How to Use the Else Block in For and While Loops in Python

For Loop Example

To create a for loop, we typically iterate over a list. In this example, we will create a for loop that iterates over a range of 10 numbers. Inside the loop, we will check if the current number (i) is equal to 5. If it is, we will print a message stating that the loop was broken and then break out of the loop.

def for_loop_example():
    for i in range(10):
        if i == 5:
            print("The loop was broken")
            break
        print(i)

    else:
        print("Loop executed perfectly")

for_loop_example()

# Output
# 0
# 1
# 2
# 3
# 4
# The loop was broken

In this case, if the for loop completes without any breaks, it will execute the else statement. Think of the else block as a success listener. In the example above, since we break out of the loop when i is equal to 5, the else block will not be executed. However, if we remove the break statement and just print i for fun, the else block will always be executed as long as the loop runs perfectly. Even if we skip number 5, the else block will still be executed.

While Loop Example

Now let’s move on to the while loop example. In this case, we will create a variable i and set it to 0. We will also create a variable is_connected and set it to True to simulate an internet connection. Inside the loop, we will check if i is equal to 5. If it is, we will set is_connected to False, simulating the disappearance of the internet. We also need to increment i by 1 in each iteration to eventually exit the loop.

def while_loop_example():
    i = 0
    is_connected = True

    while is_connected:
        if i == 5:
            is_connected = False
            print("The internet disappeared")
        i += 1

    else:
        print("The else block was executed")

while_loop_example()

# Output
# The internet disappeared
# The else block was executed

Similar to the for loop, we can specify an else block for the while loop as well. In this example, the else block will be executed. This raises questions because, unlike the for loop, the while loop does not need to finish successfully for the else block to be executed. In this case, the condition is_connected evaluates to False, allowing us to exit the loop and triggering the else block. We could have used a simpler loop structure without the is_connected variable, but we needed something to evaluate to False to trigger the else block. If we break the loop instead of setting is_connected to False, the else block will not be triggered. It is important to note that any errors or breaks inside the else block will not execute the block.

Conclusion

The else block in Python is a unique feature that can be used with both for and while loops. However, it behaves differently in each case.

In a for loop, the else block is only executed if the loop completes without any breaks. This can be useful for checking if a loop ran successfully.

In a while loop, the else block is executed if the loop exits normally, meaning that the condition evaluated to False. This can be useful for handling errors or cleaning up after the loop has finished.

It is important to note that the else block will not be executed if the loop is broken or an error occurs inside the else block itself.

If you found this article helpful and insightful, I would greatly appreciate your support. You can show your appreciation by clicking on the button below. Thank you for taking the time to read this article.

Popular Posts

Spread the knowledge
 
  

Leave a Reply

Your email address will not be published. Required fields are marked *