python:第十七章:布尔运算符(逻辑运算符)
一,布尔运算符有哪些?
and运算是与运算,只有两个值都为True,and运算结果才是True,如下表
| a | b | a and b |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
or运算是或运算,只要其中有一个值为True,or运算结果就是True
| a | b | a or b |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
not运算是非运算,它是一个单目运算符,把True变成False,False变成True
| a | not a |
|---|---|
| True | False |
| False | True |
例子:and运算符
|
1
2
3
4
5
6
|
# and运算print(True and True) # Trueprint(True and False) # Falseprint(False and False) # Falseprint(8 > 3 and 5 > 1) # Trueprint(4 > 7 and 5 > 1) # False |
运行结果:
True
False
False
True
False
例子:or运算符
|
1
2
3
4
5
6
|
# or运算print(True or True) # Trueprint(True or False) # Trueprint(False or False) # Falseprint(8 > 3 or 2 > 5) # Trueprint(4 > 7 or 5 > 9) # False |
运行结果:
True
True
False
True
False
例子:not运算符
|
1
2
3
4
5
|
# not运算print(not True) # Falseprint(not False) # Trueprint(not 1 > 3) # Trueprint(not 3 > 1) # False |
运行结果:
False
True
True
False
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/11/14/python-di-shi-qi-zhang-bu-er-yun-suan-fu/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,优先级
| 运算符 | 优先级 |
|---|---|
| not | 高 |
| and | 中 |
| or | 低 |
按照优先顺序做逻辑运算时,为了清晰可以加上括号
| 表达式 | 等价表达式 |
|---|---|
| a or b and c | a or (b and c) |
| a and b or c and d | (a and b) or (c and d) |
| a and b and c or d | ((a and b) and c) or d |
| not a and b or c | ((not a) and b) or c |

浙公网安备 33010602011771号