笨方法学python-9(习题27-29)

本文通过一系列练习介绍了布尔逻辑的基本概念及其在代码中的应用,并探讨了如何使用if语句来根据条件执行不同的代码路径。

最近沉迷于码代码无法自拔。晚上睡觉之前脑子里都是白天的代码,充实!

习题27:记住逻辑关系

  • 这部分b基本问题不大
  • and:与
  • or:或
  • not:非
  • !=:不等于
  • ==:等于
  • >=:大于等于
  • <=:小于等于
  • True:真
  • False:假

真值表

NOTTrue?
not false True
not trueFalse
ORTrue?
True or FalseTrue
True or TrueTrue
False or TrueTrue
False or FalseFalse
ANDTrue?
True and FalseFalse
True and TrueTrue
False and TrueFalse
False and FalseFalse
NOT ORTrue?
not(True or False)False
not(True or True)False
not(False or True)False
not(False or False)True
NOT ANDTrue?
not(True and False)True
not(True and False)False
not(False and True)True
not(False and False)True
!=True?
1!=0True
1!=1False
0!=1True
0!=0False
==True?
1==0False
1==1True
0==1False
0==0True


习题28:布尔表达式练习

print(True and False)   # False
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("test" != "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("test" == "testing" or "Python" == "Fun"))   # True

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

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

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

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

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

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



习题29:如果(if)

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.")

猜猜“if 语句”是什么,它有什么用处。在做下一道习题前,试着用自己的话回答下面的问题:

1. 你认为  if 对于它下一行的代码做了什么?

if后面是True才会继续执行下面的语句

2. 为什么  if 语句的下一行需要 4 个空格的缩进?

表示此代码属于这个if语句的

3. 如果不缩进,会发生什么事情?

不缩进,该语句就不受if的影响,都会执行

4. 把习题 27 中的其它布尔表达式放到``if 语句``中会不会也可以运行呢?试一下。

5. 如果把变量  people ,  cats , 和  dogs 的初始值改掉,会发生什么事情?

输出的内容根据if条件变化



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

故沉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值