Pre-requisite : for loop in Python
for-else loop in Python contains else statement specified after for loop. In for-else loop, a block of code specified under else statement is executed once the loop ends.
Syntax
for variable in sequence:
Statements
else:
Statements to be executed after loop
Let us check the working of for-else loop with the help of an example :
Program : Print following series : 1, 4, 7, 10, 13, “Inside else” using for-else loop.
# for else Illustration
for element in range(1,14,3):
print(element, end=' ')
else:
print("Inside else")
O/P :
1 4 7 10 13 Inside else
In the above program, we have used Python range() function to display all the numbers starting from 1, ending before 14, with the step size of 3. Here, ‘element‘ is our loop variable holding integer value 1, 4, 7, 10, 13. This loop runs 5 times and gets terminated after element = 13; Once terminated, statements under else block are executed. This is how for-else works in Python.
Do you know ?
Python does not supports anything like for-elif statement.
That’s all, see you in the next lecture.