为什么Python没有"continue if"语句?

cha*_*ore 6 python python-3.x

我认为这是一个非常易读的代码块,

for i in range(100):
    continue if i % 2 == 0
Run Code Online (Sandbox Code Playgroud)

但它在语法上并不正确.我们可以在Python中做其他好事,比如

for i in things:
    total += 3 if i % 2 == 0 else 1
Run Code Online (Sandbox Code Playgroud)

或者可能,

return a if b > a else c
Run Code Online (Sandbox Code Playgroud)

为什么我们不能continue if发表声明?

wim*_*wim 12

流程:

for i in range(100):
    continue if i % 2 == 0
Run Code Online (Sandbox Code Playgroud)

相当于:

for i in range(1, 100, 2):
    ...
Run Code Online (Sandbox Code Playgroud)

或者,更一般地说,:

for i in range(100):
    if i % 2 == 0:
        continue
Run Code Online (Sandbox Code Playgroud)

Python语言设计者有一个投票反对语法变化的历史,它只提供了略微不同的方法来做同样的事情("应该有一种明显的方法来做").

你提到的单线结构的类型

x if cond else y
Run Code Online (Sandbox Code Playgroud)

在这里是一个例外.它被添加到语言中,以提供一种不易出错的方式来实现许多用户已经尝试实现的目标and和or短路黑客(来源:Guido).野外代码使用:

cond and x or y
Run Code Online (Sandbox Code Playgroud)

这在逻辑上并不等同,但对于已经熟悉cond ? : x : yC语言的三元语法的用户来说,这是一个容易犯的错误.正确的等价物是:

(cond and [x] or [y])[0]
Run Code Online (Sandbox Code Playgroud)

但是,那很难看.因此,添加表达的理由x if cond else y强于仅仅是方便.