笨方法学Python(26-30)
2016-01-03 13:46
507 查看
习题26、恭喜你,现在可以考试了!
习题27、记住逻辑关系
逻辑术语and 与
or 或
not 非
!= (not equal) 不等于
== (equal) 等于
>= (greater-than-equal) 大于等于
<= (less-than-equal) 小于等于
True 真
False 假
小结
直接学习布尔算法,不用背这些东西,可不可以?
当然可以,不过这么一来,当你写代码的时候,你就需要回头想布尔函数的原理,这样你写代码的速度就慢了。而如果你记下来了的话,不但锻炼了自己的记忆力,而且让这些应用变成了条件反射,而且理解起来就更容易了。当然,你觉得哪个方法好,就用哪个方法好了。
习题28、布尔表达式练习
练习截屏技巧
所有的布尔逻辑表达式都可以用下面的简单流程得到结果:
找到相等判断的部分 (== or !=),将其改写为其最终值 (True 或 False)。
找到括号里的 and/or,先算出它们的值。
找到每一个 not,算出他们反过来的值。
找到剩下的 and/or,解出它们的值。
等你都做完后,剩下的结果应该就是 True 或者 False 了。
小结
为什么
"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了。不过还是要确保整个语句都能正常处理,以方便日后理解和使用代码。
习题29、如果(if)
#!/usr/bin/python # -*- coding:utf-8 -*- people = 20 cats = 30 dogs = 15 if people < cats: print "Too many cats! The world is doomed!" if people > cats: print "Not many cats! The world is saved!" if people < dogs: print "The world is drooled on!" if people > dogs: print "The world is dry!" dogs += 5 if people >= dogs: print "People are greater than or equal to dogs." if people <= dogs: print "People are less than or equal to dogs." if people == dogs: print "People are dogs."
小结
+=是什么意思?
x += 1和
x = x + 1一样,只不过可以少打几个字母。你可以把它叫做加值符。一样的,你后面还会学到
-=以及很多别的表达式。
习题30、Else 和 If
#!/usr/bin/python # -*- coding:utf-8 -*- people = 30 cars = 40 buses = 15 if cars > people: print "We should take the cars." elif cars < people: print "We should not take the cars." else: print "We can't decide." if buses > cars: print "That's too many buses." elif buses < cars: print "Maybe we could take the buses." else: print "We still can't decide." if people > buses: print "Alright, let's just take the buses." else: print "Fine, let's stay home then."
小结
如果多个
elif区块都是
True是 python 会如何处理?
Python 只会运行它碰到的是
True的第一个区块,所以只有第一个为
True的区块会被
运行。
相关文章推荐
- python+ueditor+七牛云存储整合
- python auto-increment
- [转]修改python默认的编码方式
- [No000078]Python3 字符串操作
- 2016/1/3 Python中的多线程(2):threading模块
- python学习笔记-Day10--(select-IO多路复用)(queue)
- python Basic Authentication
- 用python简单处理图片(1):打开\显示\保存图像
- Python性能鸡汤
- python实用技巧(三)
- leetcode之Flatten Binary Tree to Linked List
- python 代码片段7
- PyCharm的注册与使用
- python实战系列之生成随机验证码(三)
- 【python】SIR模型实现
- python 代码片段6
- Python 爬虫的实践运用(1)--爬取百度百科的词条
- python 代码片段5
- Python 决定迁移到 GitHub
- python基础知识