加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 17:00:59 所属栏目:Python 来源:网络整理
导读:上一节你学到的逻辑组合的正式名称是“布尔逻辑表达式 (boolean logic expression)” 。在编程中,布尔逻辑可以说是无处不在。它们是计算机运算的基础和重要组成部分,掌握它们就跟学音乐掌握音阶一样重要。 在这节练习中,你将在 python 里使用到上节学到的

上一节你学到的逻辑组合的正式名称是“布尔逻辑表达式 (boolean logic expression)” 。在编程中,布尔逻辑可以说是无处不在。它们是计算机运算的基础和重要组成部分,掌握它们就跟学音乐掌握音阶一样重要。


在这节练习中,你将在 python 里使用到上节学到的逻辑表达式。先为下面的每一个逻辑问题写出你认为的答案,每一题的答案要么为 True 要么为 False 。写完以后,你需要将 python 运行起来,把这些逻辑语句输入进去,确认你写的答案是否正确。


# -*- coding:utf-8 -*-

print True and True TRUE

print False and True FALSE

print 1 == 1 and 2 == 1 FALSE

print "test" == "test" TRUE

print 1 == 1 or 2 != 1 TRUE

print True and 1 == 1 TRUE

print False and 0 != 0 FALSE

print True or 1 == 1 TRUE

print "test" == "testing" FALSE

print 1 != 0 and 2 == 1 FALSE

print "test" != "testing" TRUE

print "test" == 1 FALSE

print not (True and False) TRUE

print not (1 == 1 and 0 != 1) FALSE

print not (10 == 1 or 1000 == 1000) FALSE

print not (1 != 10 or 3 == 4) FALSE

print not ("testing" == "testing" and "Zed" == "Cool Guy") TRUE

print 1 == 1 and not ("testing" == 1 or 1 == 0) TRUE

print "chunky" == "bacon" and not (3 == 4 or 3 == 3) FALSE

print 3 == 3 and not ("testing" == "testing" or "Python" == "Fun") FALSE

在本节结尾的地方我会给你一个理清复杂逻辑的技巧。


所有的布尔逻辑表达式都可以用下面的简单流程得到结果:


1. 找到相等判断的部分 (== or !=) ,将其改写为其最终值 (True 或 False) 。


2. 找到括号里的 and/or ,先算出它们的值。


3. 找到每一个 not ,算出他们反过来的值。


4. 找到剩下的 and/or ,解出它们的值。


5. 等你都做完后,剩下的结果应该就是 True 或者 False 了。


下面我们以 #20 逻辑表达式演示一下:


3 != 4 and not ("testing" != "test" or "Python" == "Python")


接下来你将看到这个复杂表达式是如何逐级解为一个单独结果的:


1. 解出每一个等值判断 :


? ? 1. 3 != 4 为 True: True and not ("testing" != "test" or "Python" == "Python")


? ? 2. "testing" != "test" 为 True: True and not (True or "Python" == "Python")


? ? 3. "Python" == "Python": True and not (True or True)


2. 找到括号中的每一个 and/or :


? ? 1. (True or True) 为 True: True and not (True)


3. 找到每一个 not 并将其逆转 :


? ? 1. not (True) 为 False: True and False


4. 找到剩下的 and/or ,解出它们的值 :


? ? 1. True and False 为 False


这样我们就解出了它最终的值为 False.


加分习题


1. Python 里还有很多和 != 、 == 类似的操作符 . 试着尽可能多地列出 Python 中的等价运算符。


如 !=? ? ==? ? >? ? >=? ? <? ? <=? ? <>??


2. 写出每一个等价运算符的名称。例如 != 叫 “ not equal (不等于)”。


3. 在 python 中测试新的布尔操作。在敲回车前你需要喊出它的结果。不要思考,凭自己的第一感就可以了。把表达式和结果用笔写下来再敲回车,最后看自己做对多少,做错多少。


4. 把习题 3 那张纸丢掉,以后你不再需要查询它了。


常见问题回答


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


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


!= 和 <> 有何不同?


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


有没有短路逻辑?


有的。任何以 False 开头的 and 语句都会直接被处理成 False 并且不会继续检查后面语句了。任何包含 True 的 or 语句,只要处理到 True 这个字样,就不会继续向下推算,而是直接返回 True 了。不过还是要确保整个语句都能正常处理,以方便日后理解和使用


代码。


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读