繁体   English   中英

当您不想中断时,如何在python 3中使用for循环else语句?

[英]How to use the for loop else statement in python 3 when you don't want to break?

这是执行以下代码的最佳方法,还是在for循环后使用else语句来实现?

moved = False
for action in actions:
    if action.type == KEY:
        moved = True
        if action.key == UP:
            move_forward()
        update_all()
if not moved:
    update_all()

对于那段特定的代码,您可以简化为:

for action in actions:
    if action.type == KEY and action.key == UP:
        move_forward()
update_all()

由于您始终在更新,因此即使您的操作不是KEY类型。

如果有任何理由要全部更新,请在for每个循环后最后进行

moved = False
for action in actions:
    if (action.type == KEY and action.key == UP):
        moved = True
        move_forward()
update_all()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM