後來屢次測試: python
>>> a=1 if x==0 else b=1
File "<stdin>", line 1
SyntaxError: can't assign to conditional expression
>>> a if x==0 else b=1
File "<stdin>", line 1
SyntaxError: can't assign to conditional expression
>>> c = a if x==0 else b
>>> express
在stack overflow找到了相似問題,http://stackoverflow.com/questions/14474168/using-statements-on-either-side-of-a-python-ternary-conditional ide
怪我基礎不紮實。還有expression和statement是什麼?expression是表達式,就是加減乘除等各類運算符號聯接起來 的式子
,statement是語句,如if語句,while,複製語句等。 函數
好了,這個問題弄明白了。 測試
第一個錯誤在expression中包含了statement,語法錯誤。第二個和第三個錯誤是由於三木運算是expression只能做爲左值,這也說明了四是正確的。 spa
在c中if(a--) 能正確執行,而python中if a-=1會報錯,這也說明了python與c的不一樣。 string
python中還有兩個函數exec和eval,這兩個函數的參數都是str,但exec執行statement,而eval執行expression。 it
>>> exec('a=1')
>>> exec('a==1')
>>> eval('a=1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
a=1
^
SyntaxError: invalid syntax
>>> eval('a==1')
True
>>> io
eval就只能執行expression了,有返回值。 ast
expression有返回值,statement沒有返回值。
記住此次的教訓,基礎的東西不可忽視,最基礎的東西可能就是之後項目中最難以解決的bug!