Python (Scripting) - Break out of a loop

by
Jeremy Canfield |
Updated: June 02 2023
| Python (Scripting) articles
- break is used to break out of a loop
- continue is used to move onto the next item in a loop
Let's say you have the following script to loop through the items in the fruits list.
#!/usr/bin/python
fruits = ["apple", "banana", "orange", "grapes"]
for item in fruits:
print(item)
Running this script will return the following. Each value in the list is printed.
apple
banana
orange
grapes
In this example, break is placed inside of the loop.
#!/usr/bin/python
fruits = ["apple", "banana", "orange", "grapes"]
for item in fruits:
print(item)
if item == 'orange':
break
Now only apply and banana will be printed.
apple
banana
Did you find this article helpful?
If so, consider buying me a coffee over at