Why Does Python Use ‘else’ After For And While Loops?

In this post we will learn Why does Python use ‘ else ‘ after for and while loops which is used for making sure that we have successfully executed the loop and that there is no error or problem or return existing in the loop for example and understand it better have a look at the example given below.

else

else Block After A Loop

As we know at times that in a loop could not get to know whether the loop was able to execute successfully or not and whether the value that we want to execute was executed or not so in those cases we have an additional block that we can add at the end of the loop and it will let us know about the successful execution of loop otherwise that loop will not be executed so here we have given an example below to understand it better.

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

In this above code the loop is going to iterate the whole loop and at the end after printing the whole list is going to spring loop is finished without break.

But here we have given another example where we can see how this additional block will help us to understand and get to know whether the loop is executed successfully or a break or return had come in between.

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

Here we can say that we have used a break statement in a loop where we have given a condition before the break statement so if the condition is true then the break statement will execute and that will lead to the exit of the loop which simply means the loop is not executed successfully here the other part will not be executed and the block of it will remain unexecuted which simply means the loop is not executed successfully.

And was the exact task for this additional else block to know the more information about the execution of the loop and its execution. In some cases we use this part for making a block to be used for the conditions given are not fully filled. And for such case we can use default statement in loops.

 

 

To learn more about Why does Python use ‘else’ after for and while loops visit:  by stack over flow

To learn more about solutions to different problems and tutorials for the concepts we need to know to work on programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & Python Client To A Linux/Ubuntu Server Which Is Running C?.

 

Leave a Comment

%d bloggers like this: