笨方法学习Python-习题28: 布尔表达式练习

来源:互联网 发布:windows截屏 编辑:程序博客网 时间:2024/06/13 22:05

目的:熟练与掌握逻辑表达式

在Python交互页面输入以下逻辑语句,确认写的答案是否正确:

True and True # TrueFalse and False # False1 == 1 and 2 == 1 # False"test" == "test" # True1 == 1 or 2 != 1 # TrueTrue or 1 == 1 # True"test" == "testing" # False1 != 0 and 2 == 1 # False"test" != "testing" # True"test" == 1 # Falsenot (True and False) # Truenot (1 == 1 and 0 != 1) # Falsenot (10 == 1 or 1000 == 1000 ) # Falsenot (1 != 10 or 3 == 4) # Falsenot ("testing" == "testing" and "Shui" == "mahua") # True1 == 1 and not ("testing" == 1 or 1 == 0) # True"chunky" == "bacon" and not (3 == 4 or 3 == 3) # False3 == 3 and not ("testing" == "testing" or "Python" == "Fun") # False

常见问题问答:

1)为什么 "test" and "test" 返回 "test", 1 and 1 返回 1,而不是返回 True 呢?

Python 和很多语言一样,都是返回两个被操作对象中的一个,而非它们的布尔表达式True 或 False 。这意味着如果你写了 False and 1 ,你得到的是第一个操作字元(False),而非第二个字元(1)。多多实验一下。


2)!= 和 <> 有何不同?

Python 中 <> 将被逐渐弃用, != 才是主流,除此以为没什么不同。


3)有没有短路逻辑?

有的。任何以 False 开头的 and 语句都会直接被处理成 False 并且不会继续检查后面语句了。任何包含 True 的 or 语句,只要处理到 True 这个字样,就不会继续向下推算,而是直接返回 True 了。

原创粉丝点击