[英]Can I break out of a for loop with a function?
我制作了一個for
循環,該循環將在使用 gpiozero 按下按鈕時生成時間表,並希望長按退出循環。
最初我以為我可以制作一個帶有break
的 function ,它會通過長按退出循環,但是由於break
在循環之外,所以我得到一個語法錯誤,不管我希望它被解釋為退出 function 而不是循環 function 被調用。
另一個想法是制作類似的東西 - 當 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()
您可以在cont
中raise
Exception 並在 for 循環中使用try/except
子句並跳出它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.