Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

loops - Why "if-else-break" breaks in python?

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.

Sample code:

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.

What is wrong in using the break command after the else keyword?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 , print was not a function either. So this would error with the print statement. In 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...