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
225 views
in Technique[技术] by (71.8m points)

python - Syntax error in ternary if-else statement

We can use if-else like this:

statement if condition else statement

but there are some problems here and I can't understand why.

  1. If I run count += 1 if True else l = [] (count is defined already), then it raises an error:

     File "<ipython-input-5-d65dfb3e9f1c>", line 1
     count += 1 if True else l = []
                               ^
     SyntaxError: invalid syntax
    

    Can we not assign a value after else?

  2. When I run count += 1 if False else l.append(count+1) (note: count = 0, l = []), an error will be raised:

     TypeError    Traceback (most recent call last)
     <ipython-input-38-84cb28b02a03> in <module>()
     ----> 1 count += 1 if False else l.append(count+1)
    
     TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
    

    and the result of l is [1].

Using the same conditions, if I use an if-else block, there are no errors.

Can you explain the difference?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The "conditional expression" A if C else B is not a one-line version of the if/else statement if C: A; else: B, but something entirely different. The first will evaluate the expressions A or B and then return the result, whereas the latter will just execute either of the statements A or B.

More clearly, count += 1 if True else l = [] is not (count += 1) if True else (l = []), but count += (1 if True else l = []), but l = [] is not an expression, hence the syntax error.

Likewise, count += 1 if False else l.append(count+1) is not (count += 1) if False else (l.append(count+1)) but count += (1 if False else l.append(count+1)). Syntactically, this is okay, but append returns None, which can not be added to count, hence the TypeError.


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

...