簡單的回答可以使用表達式4 + 5等於9,在這裡4和5被稱為操作數,+被稱為操符。 Python語言支持操作者有以下幾種類型。
算術運算符
比較(即關系)運算符
賦值運算符
邏輯運算符
位運算符
會員操作符
標識操作符
讓我們逐一看看所有的運算符。
假設變量a持有10和變量b持有20,則:
假設變量a持有10和變量b持有20,則:
假設變量持有10和變量b持有20,則:
試試下面的例子就明白了所有在Python編程語言可供選擇的賦值運算符:
#!/usr/bin/python a =21 b =10 c =0 c = a + b print"Line 1 - Value of c is ", c c += a print"Line 2 - Value of c is ", c c *= a print"Line 3 - Value of c is ", c c /= a print"Line 4 - Value of c is ", c c =2 c %= a print"Line 5 - Value of c is ", c c **= a print"Line 6 - Value of c is ", c c //= aprint"Line 7 - Value of c is ", c
當執行上面的程序,它會產生以下結果:
Line 1 - Value of c is 31 Line 2 - Value of c is 52 Line 3 - Value of c is 1092 Line 4 - Value of c is 52 Line 5 - Value of c is 2 Line 6 - Value of c is 2097152 Line 7 - Value of c is 99864
位運算符作用於位和位操作執行位。假設,如果a =60;且b =13;現在以二進制格式它們將如下:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
http://www.cnblogs.com/roucheng/
Python語言支持下位運算符
Python語言支持以下邏輯運算符。假設變量a持有10和變量b持有20則:
除了前面討論的運算符,Python成員運算符,在一個序列中成員資格的測試,如字符串,列表或元組。有兩個成員運算符解釋如下:
試試下面的例子就明白了所有的Python編程語言提供會員運算符:
#!/usr/bin/python a =10 b =20 list =[1,2,3,4,5];if( a in list ):print"Line 1 - a is available in the given list"else:print"Line 1 - a is not available in the given list"if( b notin list ):print"Line 2 - b is not available in the given list"else:print"Line 2 - b is available in the given list" a =2if( a in list ):print"Line 3 - a is available in the given list"else:print"Line 3 - a is not available in the given list"
當執行上面的程序它會產生以下結果:
Line 1 - a is not available in the given list Line 2 - b is not available in the given list Line 3 - a is available in the given list
標識符比較兩個對象的內存位置。兩個運算符標識解釋如下:
試試下面的例子就明白了所有Python編程語言提供的標識運算符:
#!/usr/bin/python a =20 b =20if( a is b ):print"Line 1 - a and b have same identity"else:print"Line 1 - a and b do not have same identity"if( id(a)== id(b)):print"Line 2 - a and b have same identity"else:print"Line 2 - a and b do not have same identity" b =30if( a is b ):print"Line 3 - a and b have same identity"else:print"Line 3 - a and b do not have same identity"if( a isnot b ):print"Line 4 - a and b do not have same identity"else:print"Line 4 - a and b have same identity"
當執行上面的程序它會產生以下結果:
Line 1 - a and b have same identity Line 2 - a and b have same identity Line 3 - a and b do not have same identity Line 4 - a and b do not have same identity
下表列出了所有運算符從最高優先級到最低。