[英]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.