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
This is because
print(a) if a > 5 else break
is a ternary operator. Ternary operators are no if
statements. These work with syntax:
<expr1> if <expr2> else <expr3>
It is equivalent to a "virtual function":
def f():
if <expr2>:
return <expr1>
else:
return <expr3>
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
.
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.
You can rewrite your code to:
a = 5
while True:
if a > 5:
print(a)
else:
break
a -= 1
You can read more about this in the documentation and PEP-308.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…