Python中的expression和statement

今天使用Python時碰到了以下問題:
>>> a=0
>>> b=0
>>> x=0
>>> a+=1 if x==0 else b+=1
  File "<stdin>", line 1
    a+=1 if x==0 else b+=1
                        ^
SyntaxError: invalid syntax
>>> 

後來屢次測試: 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


如上例,exec也可執行expression,statement本就由expression組成,且exec沒返回值。


eval就只能執行expression了,有返回值。 ast

expression有返回值,statement沒有返回值。

記住此次的教訓,基礎的東西不可忽視,最基礎的東西可能就是之後項目中最難以解決的bug!

相關文章
相關標籤/搜索