Python break | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Python break

Released is a dict For i in released: If "s" in released: Print(yes) Break Else: Print(not found) Why to use break here

17th Jul 2019, 11:33 AM
I Am Anushka
2 Answers
+ 1
When you loop through a dictionary like this, the variable i will become one of the dict keys (in non-determined order). So it does not make sense to iterate again through all dictionary elements in the next line, you should just write: if i == "s": Also an easy way to check if a key exists in a dictionary: d = {1: 'one', 2: 'two'} print(1 in d) # True print(3 in d) # False
17th Jul 2019, 12:40 PM
Tibor Santa
Tibor Santa - avatar
0
Here, this code checks if "s" is in the list. If it is matched once, you know that "s" is in the list, so you don't need to go further and you can escape the loop using keyword break. Imagine the list is containing one billion of elements, and "s" can be matched at index 3. Do you really need to go further and check all elements in the list? It's a waste of time, so break the loop.
17th Jul 2019, 12:23 PM
Théophile
Théophile - avatar