python not、and、or的含义以及优先级
对象 | 返回结果 | 优先顺序 |
---|---|---|
not x | if x is false,then True,else False | 1 |
x and y | if x is false,then x,else y | 2 |
x or y | if x is false,then y,else x | 3 |
- 含义:not是 “非” ;and是 “与” ;or是 “或” (可以用数学去理解)
1、not True = False 或者 not False = True (非真就是假,非假即真)
2、and是一假则假,两真为真,两假则假
3、or是一真即真,两假即假,两真则真 - 优先级是 not > and > or
代码如下(示例):
x=1 #将x赋值为1 y=0 #将y赋值为0 z=0 #将z赋值为0 print(x or y and not z) ''' 输出结果为 1 '''
小提示: 我们知道在编程语言中“非0即是True”,也就是“0为False,1为True”
- 由于优先级是not>and>or,所以首先执行not z(也就是not 0),
即 not 0 = not False =True =1下一步是轮到了and,那么 y and 1(已知y=0)即 0 and 1,也就是
False and True (假与真),我们刚刚谈过and,一假即假,故
y and 1 = 0 and 1 = False = 0最后一步按优先级是轮到了or,即 x or 0(已知x=1),
即 1 or 0 =True or Flase =True = 1(or即“或”中,一真即真)
所以输出结果为 1 - 总结: 代码运算过程为: (用数学符号表示优先级)
{ x or [ y and (not z) ] }