Using Else With For Loops
In this tutorial, we are going to see the implementation of for loop with an else statement. We will divide the tutorial into a few sections, including how, why, and when to use it for else statement. So, let us start with the basics. In most programming languages, an else statement is directly linked to an if statement and cannot be used separately. The use of "if" is a must for else in them. As we know that Python is more flexible in every aspect than the other ones, so in Python, we can use else without an if. Python allows us to implement the else functionality with for loops.
How can we implement for-else in Python?
We have to write an else statement using the Else keyword, followed by a colon after the for loop block of code.
Syntax:
When we use else with for loop, the compiler will only go into the else block of code when two conditions are satisfied:
- The loop is normally executed without any error.
- We are trying to find an item that is not present inside the list or data structure on which we are implementing our loop.
Except for these conditions, the program will ignore the else part of the program. For example, if we are just partially executing the loop using a break statement, then the else part will not execute. So, a break statement is a must if we do not want our compiler to execute the else part of the code.
For Example:
Output:
In the code above, we iterate over the list and print each element. Since we let the loop complete normally, the else statement is also executed, and "statement successfully executed" is printed. Conversely, if we stop the loop by using the break statement, then the else block will not execute.
Why do we implement the else functionality with for loops?
We mostly use such implementations in our program when we want to encounter less logical errors and want to know that our program is functioning correctly. In such cases, we will most probably send a print statement inside the code, and based on its execution, we could see if our code is working correctly. In bigger-level projects, there are more chances of bugs occurrence, so we try to implement as many such techniques as possible so we do not have to spend too much time debugging. This will help us to know if our loop is functioning properly or not.
In this tutorial, we learned the implementation of the loop-else statement and the concept behind it. There is no such case where the use of else statement with for loop is mandatory. It is completely optional. Without using else, we can also set a flag that checks if any of the values met the condition or not. We use the else with a loop because it makes the code more elegant and readable.
Comments
Post a Comment