Loop else in Python

So as you already know what is else in an if-else statement. In Python, you can also use else with for and while loops. The loop else runs only if the loop finishes all its work normally. This means it will not run if you stop the loop early using break a statement. In this blog, we will explore to use the else clause in loops, and how it can make your programs even better.

Loop else in Python
Loop else in Python

What Are Loops?

Loops are used to repeat a code block multiple times and Python only contain two types of loops:

  1. For Loopsfor loop traverse through a sequence or collection like a list or a range of numbers.
  2. While Loopswhile loops keep running again and again until a certain condition becomes False.
Example of a For Loop

Here’s a simple example of a for loop:

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

# Output:
# 0
# 1
# 2
# 3
# 4
Python

This loop will print the number from 0 to 4. As the range(5) function generates a sequence of numbers from 0 to 4.

Example of a While Loop

Now, let’s look at a while loop:

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

# Output:
# 0
# 1
# 2
# 3
# 4
Python

This loop will also print the numbers 0 to 4. It keeps executing the loop as long as count is less than 5.

What Is the else Clause?

The else clause in a loop is a code block that runs after the loop has completed all its loop or iterations without encountering a break statement. If the loop is exited normally (i.e., it finishes all its loop), the code in the else block will execute. If the loop is interrupted by a break, the else block will not run.

How Does It Work?

Let me show you how the else clause works with a for loop:

for number in range(5):
    print(number)
else:
    print("Loop finished without a break.")

# Output:
# 0
# 1
# 2
# 3
# 4
# Loop finished without a break.
Python

In this example, this loop first prints the numbers from 0 to 4, and after completing all the loops or iterations it will print "Loop finished without a break.".

Now, this similar behavior will not work with break because you already know the behaviour of break which is Python stops the loop immediately after encountering break.

For example:

for number in range(5):
    if number == 3:
        break
    print(number)
else:
    print("Loop finished without a break.")

# Output:
# 0
# 1
# 2
Python

In this case, the loop will print 01, and 2. But when it reaches 3, it hits the break statement and stops. Because the loop didn’t finish normally, the else block will not run. So, nothing will be printed after the loop.

Similarly for while loop:

count = 0
while count < 5:
    print(count)
    count += 1
else:
    print("Count reached 5.")

# Output:
# 0
# 1
# 2
# 3
# 4
# Count reached 5.
Python

Here, the loop will print numbers from 0 to 4, and then it will print "Count reached 5." This happens because the loop finished normally.

The else clause can be very useful. Like, if you are looking for something in a list, you can use the else clause to know if you found it or not.

For example: we want to find a number in a list:

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

for number in numbers:
    if number == search_for:
        print(f"Found {search_for}!")
        break
else:
    print(f"{search_for} not found in the list.")

# Output:
# 6 not found in the list.
Python

In this example, we are looking for the number 6. As it’s not in the list, the loop will finish without finding it, and the else block will run and print "6 not found in the list.".

Conclusion

The else clause in loops is a handy tool in Python. It helps you know what happens after a loop finishes. By understanding how it works, you can write better and more efficient code.

Loop else in Python

No break encountered

1 / 4

When does the else clause run in a loop?

Stops immediately

2 / 4

What happens if a break statement is encountered inside a loop?

No break causes execution

3 / 4

Which of the following is true about the else clause in loops?

After normal completion

4 / 4

In which scenario is the else block most useful in loops?

Your score is

The average score is 0%

0%

Leave a Reply

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