笨方法学习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 了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值