What is loop-else clause in Python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is loop-else clause in Python?

4th Jan 2020, 4:31 AM
Lalit kumar
Lalit kumar - avatar
5 Answers
+ 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.
4th Jan 2020, 5:29 AM
Tibor Santa
Tibor Santa - avatar
+ 3
4th Jan 2020, 7:10 AM
Ipang
4th Jan 2020, 7:01 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Thank you
4th Jan 2020, 7:34 AM
Lalit kumar
Lalit kumar - avatar
+ 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).
4th Jan 2020, 6:57 AM
Ipang