I don't understand why this is allowed in python?
>>> for i in []:
... print(i)
... else:
... print('here')
...
here
should this not have else without if syntax error? The else operates every time too (if the for has iterated or not) so its not connected.
>>> for i in 1,2,3:
... print(i)
... else:
... print('here')
...
1
2
3
here
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
else is executed if we don't break from for.
This can be useful in situation and can help us by saving us from the effort of making flags.
Example:
if we want to execute some code if we don't break from for loop, then normally we would have to do
flag = 0
for i in [1,2,3]:
if condition:
flag = 1
break
if flag == 0:
do stuff
we can instead do
for i in [1,2,3]:
if condition:
break
else:
do stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With