Bootstrap FreeKB - Python (Scripting) - Break out of a loop
Python (Scripting) - Break out of a loop

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 59a6fd in the box below so that we can be sure you are a human.