在Python中很多运算都涉及到先运算哪个程序后运算哪个的问题,下面我介绍一下Python中比较运算符的使用,详细讲解一下Python学习当中的基本知识。和经常遇到的问题。
先了解一下 运算符优先级的表
运算符优先级
| 运算符 |
描述 |
| lambda |
Lambda表达式 |
| or |
布尔“或” |
| and |
布尔“与” |
| not x |
布尔“非” |
| in,not in |
成员测试 |
| is,is not |
同一性测试 |
| <,<=,>,>=,!=,== |
比较 |
| | |
按位或 |
| ^ |
按位异或 |
| & |
按位与 |
| <<,>> |
移位 |
| +,- |
加法与减法 |
| *,/,% |
乘法、除法与取余 |
| +x,-x |
正负号 |
| ~x |
按位翻转 |
| ** |
指数 |
| x.attribute |
属性参考 |
| x[index] |
下标 |
| x[index:index] |
寻址段 |
| f(arguments...) |
函数调用 |
| (experession,...) |
绑定或元组显示 |
| [expression,...] |
列表显示 |
| {key:datum,...} |
字典显示 |
| 'expression,...' |
字符串转换 |
架设你要运算5+ 2 * 3那样的表达式,是先做加法还是乘法?我们的中学数学告诉我们先乘除后加减——这就意味着乘法运算符的优先级高于加法运算符。
下面这个表给出
python的运算符优先级,从最低的优先级(最松散地结合)到最高的优先级(最紧密地结合)。这意味着在一个表达式中,Python会首先计算表中较下面的运算符,然后在计算列在表上部的运算符。
上表可以看出(与Python参考手册中的那个表一模一样)已经顾及了完整的需要。事实上,我建议你使用圆括号来分组运算符和操作数,以便能够明确地指出运算的先后顺序,使程序尽可能地易读。例如,5 + (2 * 3)显然比5 +2 * 3清晰。与此同时,圆括号也应该正确使用,而不应该用得过滥(比如5 + (2 +3)),一定不要这样使用。
试试下面的例子就明白了所有的Python编程语言提供的比较操作符:
a = 21
b = 10
c = 0
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
print "Line 3 - a is equal to b"
if ( a < b ):
print "Line 4 - a is less than b"
else:
print "Line 4 - a is not less than b"
if ( a > b ):
print "Line 5 - a is greater than b"
else:
print "Line 5 - a is not greater than b"
a = 5;
b = 20;
if ( a <= b ):
print "Line 6 - a is either less than or equal to b"
else:
print "Line 6 - a is neither less than nor equal to b"
if ( b >= a ):
print "Line 7 - b is either greater than or equal to b"
else:
print "Line 7 - b is neither greater than nor equal to b"
执行后程序得到以下运算结果
Line 1 - a is not equal to b
Line 2 - a is not equal to b
Line 3 - a is not equal to b
Line 4 - a is not less than b
Line 5 - a is greater than b
Line 6 - a is either less than or equal to b
Line 7 - b is either greater than or equal to b