笨方法学Python(26-30)

习题26、恭喜你,现在可以考试了!


习题27、记住逻辑关系

逻辑术语

  • and 与
  • or 或
  • not 非
  • != (not equal) 不等于
  • == (equal) 等于
  • >= (greater-than-equal) 大于等于
  • <= (less-than-equal) 小于等于
  • True 真
  • False 假

小结

  1. 直接学习布尔算法,不用背这些东西,可不可以?
    当然可以,不过这么一来,当你写代码的时候,你就需要回头想布尔函数的原理,这样你写代码的速度就慢了。而如果你记下来了的话,不但锻炼了自己的记忆力,而且让这些应用变成了条件反射,而且理解起来就更容易了。当然,你觉得哪个方法好,就用哪个方法好了。

习题28、布尔表达式练习

练习截屏

练习截屏

技巧

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

  1. 找到相等判断的部分 (== or !=),将其改写为其最终值 (True 或 False)。
  2. 找到括号里的 and/or,先算出它们的值。
  3. 找到每一个 not,算出他们反过来的值。
  4. 找到剩下的 and/or,解出它们的值。
  5. 等你都做完后,剩下的结果应该就是 True 或者 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并且不会继续检查后面语句了。任何包含Trueor语句,只要处理到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."

小结

  1. +=是什么意思?
    x += 1x = 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."

小结

  1. 如果多个elif区块都是True是 python 会如何处理?
    Python 只会运行它碰到的是True的第一个区块,所以只有第一个为True的区块会被
    运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值