“for-else” In Python Explained

In almost all the programming languages, the else logical clause is tightly associated with the if clause. The else block can be used only within the context of if construct and executes when the test condition found to be False. However, in Python the else can be used along with the frequently used repetition construct for loop to write a concise code. Let’s understand how this idea works.

Consider the following simple example which checks whether the number input from the user falls within the range of 10.

Traditional if-else Way (Incorrect)

n = int(input('Enter a number: '))

for i in range(10): # range(n) returns a list of integers from 0 to n-1
    if(n == i):
        print('Found within the range')

    else:
        print('Not found within the range')
OUTPUT:
Enter a number: 5
Not found within the range
Not found within the range
Not found within the range
Not found within the range
Not found within the range
Found within the range
Not found within the range
Not found within the range
Not found within the range
Not found within the range

As we can see, the output is correct at the sixth iteration when the value of iterator variable i becomes 5, and the rest of the times the output is incorrect. To fix it, we can make use of a flag variable.

The Right Way Using a Flag

n = int(input('Enter a number: '))

FLAG = False

for i in range(10):
    if(i == n):
        FLAG = True

if(FLAG == True): # if(FLAG) to be more concise
    print('Found within the range')
else:
    print('Not found within the range')
OUTPUT:
Enter a number: 5
Found within the range

============= RERUN =============
Enter a number: 14
Not found within the range

That’s fine, however the same if-else logical comparison was still required to be written outside of the for loop. This is where the Python shines…

Concise for-else Way (Pythonic)

n = int(input('Enter a number: '))

for i in range(10):
    if(i == n):
        print('Found within the range')
        break

else:    # else block is outside the loop and at the same level as the for block
    print('Not found within the range')
OUTPUT:
Enter a number: 7
Found within the range

============= RERUN =============
Enter a number: 35
Not found within the range

Here are the key observations:

  • else block is outside the for loop.
  • else block is at the same scope level as the for loop. And hence it’s execution is depends on what happens inside the for loop.
  • The hero in the driver’s seat here is break who makes the above code work. If break statement gets executed (when the input number is between 0-9), the else block is skipped. Otherwise, the else block is executed.

This is much like the if-else way of comparing, but the test condition now is whether or not the break statement within the loop gets executed. Thus break acting as the if condition for the else block.

Same “else” logic works in the case of “while” loop.

So next time you encounter a situation where you have to make a decision depending on what happens within the loop, do use else along with the looping construct of your choosing (for or while). It’s precise, concise and elegant.

There’s no “do while” loop construct in Python.

If you know other use cases of for-else or while-else, let me know in the comment section below.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s