if: else: 和 if: continue 之间的区别

lea*_*tar 9 python loops if-statement continue

假设我有一个可迭代的:球。我想对该循环中所有非蓝色的球做一些事情。据我所知,我有两个选择:

使用 if: else:

for ball in balls:
    if ball.blue:
        # can do something with blue ball
    else:
        # now execute code for all balls that are not blue
Run Code Online (Sandbox Code Playgroud)

使用 if: 继续

for ball in balls:
    if ball.blue:
        # can do something with blue ball
        continue
    # now execute code for all balls that are not blue
Run Code Online (Sandbox Code Playgroud)

对我来说,这两种结构所能实现的目标没有区别。是否存在有意的差异?是否存在更快、更具可读性等的情况?

And*_*cus 2

在您所展示的情况下,没有区别,因为 if-else 语句后没有逻辑。通常continue用于跳到 for 循环的另一次迭代,因此在以下情况下您将无法如此轻松地翻译它:

for ball in balls:
    if ball.blue:
        # can do something with blue ball
    else:
        # now execute code for all balls that are not blue
    # here some logic
Run Code Online (Sandbox Code Playgroud)

如果您在 的末尾替换else为,则将无法到达最后一行。continueif