布尔表达式练习
上一节你学到的逻辑组合的正式名称是“布尔逻辑表达式(boolean logic expression)”。在编程中,布尔逻辑可以说是无处不在。它们是计算机运算的基础和重要组成部分,掌握它们就跟学音乐掌握音阶一样重要。
在这节练习中,你将在 python 里使用到上节学到的逻辑表达式。先为下面的每一个逻辑问题写出你认为的答案,每一题的答案要么为 True 要么为 False。写完以后,你需要将 python 运行起来,把这些逻辑语句输入进去,确认你写的答案是否正确。
True and True #真的
False and True #假的
1 == 1 and 2 == 1 #假的
"test" == "test" #真的
1 == 1 or 2 != 1 #真or真=真
True and 1 ==1 #真 and 真=真
False and 0 != 0 #假 and 假=假
True or 1 == 1 #真 or真 =真
"test" != "testing" #真
"test" == 1 #假
not (True and False) #not(假)=真
not(10 == 1 or 1000 == 1000)#not(假or真)=not(真)=假的
not ("testing" == "testing"and "Zed"=="Cool Guy")#not(真 and 假)=not(假)=真
1 == 1 and not("testing" ==1 or 1 == 0) #真 and not(假 or 假)=真 and not(假)=真 and 真=真
"chunky" == "bacon" and not (3 == 4 or 3 == 3) #假 and not(假 or 真)=假 and not(假)=假 and 真=假
3 == 3 and not("testing" == "testing" or "Python" == "Fun") #真 and not(真 or 假)=真 and not(真)=真 and 假=假
编译器运行
Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> True and True
True
>>> False and True
False
>>>
KeyboardInterrupt
>>> 1 == 1 and 2 == 1
False
>>> "test" == "test"
True
>>> 1 == 1 or 2 != 1
True
>>> True and 1 ==1
True
>>> False and 0 != 0
False
>>> True or 1 == 1
True
>>> "test" != "testing"
True
>>> "test" == 1
False
>>> not (True and False)
True
>>> not(10 == 1 or 1000 == 1000)
False
>>> not ("testing" == "testing"and "Zed"=="Cool Guy")
True
>>> 1 == 1 and not("testing" ==1 or 1 == 0)
True
>>> "chunky" == "bacon" and not (3 = 4 or 3 == 3)
File "<stdin>", line 1
"chunky" == "bacon" and not (3 = 4 or 3 == 3)
^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
>>> "chunky" == "bacon" and not (3 == 4 or 3 == 3)
False
>>> 3 == 3 and not("testing" == "testing" or "Python" == "Fun")
False
注意:编译器进行真假判断必须使用双等于号 “==”。
常见问题回答
Q1:为什么 "test" and "test" 返回 "test", 1 and 1 返回 1,而不是返回 True 呢?
>>> "test" and "test"
'test
>>> 1 and 1
1
A1:Python 和很多语言一样,都是返回两个被操作对象中的一个,而非它们的布尔表达式 True 或 False 。这意味着如果你写了 False and 1 ,你得到的是第一个操作字元 (False),而非第二个字元(1)。多多实验一下。
Q2:使用>= <=进行布尔运算
Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 <= 3
True
>>> 2>=1
True
Q3:!= 和 <> 有何不同?
A3:Python 中 <> 将被逐渐弃用, != 才是主流,除此以为没什么不同。
Q4:有没有短路逻辑?
A4:有的。任何以 False 开头的 and 语句都会直接被处理成 False 并且不会继续检查后面语句了。任何包含 True 的 or 语句,只要处理到 True 这个字样,就不会继续向下推算,而是直接返回 True 了。不过还是要确保整个语句都能正常处理,以方便日后理解和使用代码。