微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我可以用函数跳出 for 循环吗?

如何解决我可以用函数跳出 for 循环吗?

我制作了一个 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()

解决方法

您可以在 raisecont 一个异常,并在您的 for 循环中包含一个 try/except 子句并跳出它。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。