python运算符
Python算术运算符
| ** | 幂 - 返回x的y次幂 | a**b 为10的20次方, 输出结果 100000000000000000000 |
| // | 取整除 - 返回商的整数部分 | 9//2 输出结果 4 , 9.0//2.0 输出结果 4.0 |
Python赋值运算符
| **= | 幂赋值运算符 | c **= a 等效于 c = c ** a |
| //= | 取整除赋值运算符 | c //= a 等效于 c = c // a |
Python逻辑运算符
注意:python布尔为True和False,第一个字母大写
| 运算符 | 描述 | 实例 |
|---|---|---|
| and | 布尔"与" - 如果x为False,x and y返回False,否则它返回y的计算值。 | (a and b) 返回 true。 |
| or | 布尔"或" - 如果x是True,它返回True,否则它返回y的计算值。 | (a or b) 返回 true。 |
| not | 布尔"非" - 如果x为True,返回False。如果x为False,它返回True。 | not(a and b) 返回 false。 |
Python成员运算符
| 运算符 | 描述 | 实例 |
|---|---|---|
| in | 如果在指定的序列中找到值返回True,否则返回False。 | x 在 y序列中 , 如果x在y序列中返回True。 |
| not in | 如果在指定的序列中没有找到值返回True,否则返回False。 | x 不在 y序列中 , 如果x不在y序列中返回True。 |
例子:
#!/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 not in list ): print "Line 2 - b is not available in the given list" else: print "Line 2 - b is available in the given list" a = 2 if ( 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身份运算符
身份运算符用于比较两个对象的存储单元
| 运算符 | 描述 | 实例 |
|---|---|---|
| is | is是判断两个标识符是不是引用自一个对象 | x is y, 如果 id(x) 等于 id(y) , is 返回结果 1 |
| is not | is not是判断两个标识符是不是引用自不同对象 | x is not y, 如果 id(x) 不等于 id(y). is not 返回结果 1 |
#!/usr/bin/python a = 20 b = 20 if ( 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 = 30 if ( 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 is not 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
Python运算符优先级
以下表格列出了从最高到最低优先级的所有运算符:
| 运算符 | 描述 |
|---|---|
| ** | 指数 (最高优先级) |
| ~ + - | 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@) |
| * / % // | 乘,除,取模和取整除 |
| + - | 加法减法 |
| >> << | 右移,左移运算符 |
| & | 位 'AND' |
| ^ | | 位运算符 |
| <= < > >= | 比较运算符 |
| <> == != | 等于运算符 |
| = %= /= //= -= += *= **= | 赋值运算符 |
| is is not | 身份运算符 |
| in not in | 成员运算符 |
| not or and | 逻辑运算符 |
浙公网安备 33010602011771号