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

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

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

True and True # True

False and False # False

1 == 1 and 2 == 1 # False

"test" == "test" # True

1 == 1 or 2 != 1 # True

True or 1 == 1 # True

"test" == "testing" # False

1 != 0 and 2 == 1 # False

"test" != "testing" # True

"test" == 1 # False

not (True and False) # True
not (1 == 1 and 0 != 1) # False
not (10 == 1 or 1000 == 1000 ) # False
not (1 != 10 or 3 == 4) # False
not ("testing" == "testing" and "Shui" == "mahua") # True

1 == 1 and not ("testing" == 1 or 1 == 0) # True

"chunky" == "bacon" and not (3 == 4 or 3 == 3) # False

3 == 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 了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章