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 must for else in them. As we know that Python is more flexible in every aspect than the other one's, so in Python, we can use else without an if. Python allows us to implement the else functionality with for loops.
We have to write an else statement using the Else keyword, followed by a colon after the ending of the for loop block of code.
for x in n: #statements else: #statements
When we use else with for loop the compiler will only go into the else block of code when two conditions are satisfied:
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 i in ['C','O','D','E']: print(i) else: print("Statement successfully executed")
C O D E Statement successfully executed
In the code above, we iterate over the list and print each element. Since we let the loop complete normally, the else statement 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.
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 loop-else statement and learned 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.
khana = ["roti", "Sabzi", "chawal"] for item in khana: if item == "rotiroll": break else: print("Your item was not found")
Harry Bhai meri aakho ki aatma tript hogyi
No downloadable resources for this video. If you think you need anything, please post it in the QnA!
Any Course related announcements will be posted here