简体   繁体   English

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

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

Is this the best way to execute the following code or is there a way to do it with an else statement after the for loop? 这是执行以下代码的最佳方法,还是在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 that specific piece of code you could reduce to: 对于那段特定的代码,您可以简化为:

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

Since you're always updating, even if your action is not of type KEY. 由于您始终在更新,因此即使您的操作不是KEY类型。

If there's any reason to update all, do it at the end after the for each loop 如果有任何理由要全部更新,请在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.

相关问题 Python-无法使用break语句时该怎么办? - Python - what to do when you can't use the break statement? 如何使用多处理处理带有 break 语句的 Python for 循环? - How to use multiprocessing for a Python for loop with a break statement? Python3:for循环中断和else(if语句) - Python3: for-loop break and else (if statement) 当第 1 轮结束时,我希望它循环 5 轮,然后使用 break 语句停止,然后 if else 结束 - When round 1 ends I want it to loop 5 rounds then a break statement so it stops, then the if else ending 如果要使for循环始终完成,如何使用For Else? - How to use For Else if you want the for loop to always finish? 如何在另一个模块中设置断点(不要在函数定义行设置,如果你想在函数开始执行时中断) - How to set breakpoint in another module (don't set it on function definition line, if you want to break when function starts being executed) 如何在if和else语句(在python中)中定义for循环的结果? - How can you define a for loop's outcome in an if and else statement (in python)? Python - break 语句在 while 循环内的 else 语句中不起作用 - Python - break statement not working in else statement within while loop 当你在 python 中不需要索引时,你如何制作 For 循环? - how do you make a For loop when you don't need index in python? 发生 True 时循环不会中断 - loop don't break when True occurs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM