Can I break out of a for loop with a function?

92 views Asked by At

I've made a for loop that will do times tables at the press of a button using gpiozero and want to make a long press exit the loop.

Initially I thought I could make a function with a break in it that would exit the loop with a long press but as the break is outside of the loop I get a syntax error, regardless I expect it would be interpreted as exiting the function rather than the loop the function is called in.

Another idea is to make something like - when false exit all loops - and the command in the for loop switches that condition to false. This isn't something I've covered in any tutorials and am not sure what terminology I would search to find out if this can be done.

How can I achieve this?

import gpiozero
import time
from signal import pause

button = gpiozero.Button(2, hold_time=0.5) 
#button wired to gpio 2, long press activates after .5 seconds

a = int(input('Choose a number: '))

print('Press the button to do times tables.')
print('Hold the button to tell maths to quit.')

def cont():
    print('quit maths') 
#this is where I initially tried to use a break

for x in range(1, 13):
    button.wait_for_press()
    button.when_held = cont
    button.wait_for_release()
    print('7 x', x, '=', x * a, flush=True)

pause()
1

There are 1 answers

0
sureshvv On

You can raise an Exception inside cont and have a try/except clause inside your for loop and break out of it.