+ 1
What is loop-else clause in Python?
5 ответов
+ 3
Yes in Python you can have else clause associated with for loop. It activates only if the loop completed fully, without breaking from the cycle. Example:
for item in search_list:
if item == find_this:
print('found')
break
else:
print('not found')
Here the 'else' is indented at the same level as 'for' and it will only activate at the end, if the break was never encountered.
+ 3
Thanks Tibor Santa
+ 2
This is valid syntax
https://book.pythontips.com/en/latest/for_-_else.html
+ 2
Thank you
+ 1
Tibor Santa
I didn't know about that. But wouldn't it cause an error when an `else` block is on a different indent level to the `if` block? For this typical search cases I'm used to utilise a boolean flag to indicate search result (found/not found).