为什么要"if-else-break"打破了蟒蛇? [英] Why "if-else-break" breaks in python?
问题描述
我正在尝试使用if-else表达式,如果 if
条件失败,则该表达式会中断循环,但会出现无效语法
错误.
I am trying to use if-else expression which is supposed to break the loop if the if
condition fails, but getting an invalid syntax
error.
示例代码:
a = 5
while True:
print(a) if a > 0 else break
a-=1
当然,如果我以传统方式书写(不使用一根衬纸),则可以使用.
Of course, if I write in the traditional way (not using the one liner) it works.
请让我知道在 else
关键字后使用 break
命令有什么问题.
Please let me know what is wrong in using the break
command after the else
keyword.
推荐答案
如果运行此命令,则会出现以下错误:
If I run this, I get the following error:
... print(a) if a > 0 else break
File "<stdin>", line 2
print(a) if a > 0 else break
^
SyntaxError: invalid syntax
这是因为
print(a) if a > 5 else break
是三元运算符.三元运算符是没有 if
语句.这些使用语法:
is a ternary operator. Ternary operators are no if
statements. These work with syntax:
<expr1> if <expr2> else <expr3>
与虚拟功能" 等效:
def f():
if <expr2>:
return <expr1>
else:
return <expr3>
所以这意味着 else
旁边的部分应该是表达式. break
是不是表达式,它是一个语句.因此,Python并不希望如此.您不能返回
一个中断
.
So that means the part next to the else
should be an expression. break
is not an expression, it is a statement. So Python does not expect that. You can not return
a break
.
在python-2.x , print
都不是函数.因此,这将与 print
语句一起出现错误.在python-2.x print
是关键字.
In python-2.x, print
was not a function either. So this would error with the print
statement. In python-2.x print
was a keyword.
您可以将代码重写为:
a = 5
while True:
if a > 5:
print(a)
else:
break
a -= 1
您可以在文档中了解有关此内容的更多信息, PEP-308 .
You can read more about this in the documentation and PEP-308.
这篇关于为什么要"if-else-break"打破了蟒蛇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!