break out of a loop
|Description:||Exits or Breaks out of a for or while loop|
|Related:||for, while, if, if else, continue|
The break command is used inside a for or while loop to exit from the loop. The program will skip the rest of the loop and continue at the first command after the loop block.
print 'Self destruct sequence initiated'
print ' you have 10 seconds to evacuate'
a = 10
while 1: # Run the loop, each time reducing a by 1
a = a - 1
if a == 0:
print ' ! KABOOM !'
if inp(P1_3) == 0: # Look at the switch, if pressed the value will be 0
break # and break out of the loop
print 'Self destruct sequence aborted'
When the above example runs it will run through the loop decreasing a by one each time, but if the switch on P1_3 is pressed it will cause the program to exit out of the loop. The break command will cause the program to exit out of the innermost while or for loop.