问题描述
我制作了一个 for
循环,该循环将使用 gpiozero 按下按钮来生成时间表,并希望长按退出循环。
最初我想我可以创建一个带有 break
的函数,长按会退出循环,但由于 break
在循环之外,我得到一个语法错误,不管我期望它会被解释为退出函数而不是调用函数的循环。
另一个想法是做类似的事情 - 当 false 退出所有循环时 - for
循环中的命令将该条件切换为 false。这不是我在任何教程中介绍的内容,我不确定我会搜索哪些术语来确定是否可以做到这一点。
我怎样才能做到这一点?
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()
解决方法
您可以在 raise
内 cont
一个异常,并在您的 for 循环中包含一个 try/except
子句并跳出它。