From the docs
* The else clause executes after the loop completes normally. This means that the loop did not encounter a break statement.*
So this is useful if you are doing a for loop but do not know if the element will be found in the loop/ returned true in the loop. So you can add a break statement to exit the loop if the element is found/true, or execute another command if it is not found/true. For example in your loop:
for i in []:
print(i)
else:
print('here')
Output
here
In this case, i was not found in your for loop. However you did not execute a break statement after the for loop. Because of that, the compiler then goes to the else
statement to executes the line(s) there since the for loop did not break.
In the second example you have:
for i in 1,2,3:
print(i)
else:
print('here')
Output
1
2
3
here
The for loop did not encounter a break statement, so after the for loop is completed it will then execute the else clause. However it you were to use:
for i in 1,2,3:
print(i)
break
else:
print('here')
Output :
1