Searching & break, explained simply
If you are looking for your shoes, you stop searching once you find them. A loop can do the same thing with break.
break ends the loop immediately, even if there are items left. The program then carries on with the first line after the loop.
A common pattern is to loop through a list, check each item with if, and break when you find a match. You can use a variable to remember whether you found anything at all.
Example: Find the compass
places = ["tent", "river", "cave", "hill"]
for place in places:
print("Checking the", place)
if place == "cave":
print("Found the compass!")
breakOutput
Checking the tent
Checking the river
Checking the cave
Found the compass!The hill is never checked because break stopped the loop.
Try this
- Remove break and see how the output changes.
- Search for something that is not in the list and print "Not found" at the end.
- Use break inside a while True loop to stop when the player types "quit".
