苦练Python第7天:布尔七日斩
作者:Rahul Gupta
译者:倔强青铜三
前言
大家好,我是倔强青铜三 。是一名热情的软件工程师,我热衷于分享和传播IT技术,致力于通过我的知识和技能推动技术交流与创新,欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!
欢迎来到 100天Python挑战 第7天!
今天我们要让代码学会"自己思考"------用布尔值和逻辑运算符做出判断。掌握它们,if语句才能真正活起来。
📦 今日速览
- 布尔类型:
True
、False
- 比较运算符速查
- 逻辑运算符:
and
、or
、not
- 组合条件与实战案例
- 真假值的隐式规则
✅ 什么是布尔值?
布尔(Boolean)只有两位居民:
python
True
False
大小写敏感,true
会报错。可直接赋给变量:
python
is_sunny = True
is_raining = False
🧠 返回布尔值的比较
Python 表达式天生会"判官":
python
x = 5
print(x > 3) # True
print(x == 10) # False
print(x != 7) # True
常用比较运算符
运算符 | 含义 | 示例 | 结果 |
---|---|---|---|
== |
等于 | 5 == 5 |
True |
!= |
不等于 | 3 != 2 |
True |
> |
大于 | 4 > 2 |
True |
< |
小于 | 5 < 3 |
False |
>= |
大于等于 | 5 >= 5 |
True |
<= |
小于等于 | 2 <= 1 |
False |
🔗 逻辑运算符三连招
1️⃣ and
------所有条件为真才为真
python
age = 20
is_student = True
print(age > 18 and is_student) # True
2️⃣ or
------任一条件为真即为真
python
print(age > 18 or is_student == False) # True
3️⃣ not
------真假颠倒
python
print(not is_student) # False
🔍 实战:折扣判定
python
age = 16
has_coupon = True
if age < 18 or has_coupon:
print("You get a discount!")
else:
print("Sorry, no discount.")
输出:
arduino
You get a discount!
🧪 彩蛋:真假值的隐式规则
Python 把下列值视为 False
:
- 空字符串
""
- 零
0
、0.0
- 空容器
[] {} set()
None
其余皆为 True
。
python
print(bool("")) # False
print(bool("Hi")) # True
print(bool(0)) # False
print(bool(42)) # True
利用这一特性可以精简代码:
python
name = ""
if not name:
print("Please enter your name.")
🚀 今日复盘
- 认识
True
、False
- 掌握比较运算符
- 用
and
、or
、not
组合条件 - 在
if
中写出更智能的判断 - 利用隐式真假值写更简洁的代码
最后感谢阅读!欢迎关注我,微信公众号 :
倔强青铜三
。欢迎点赞
、收藏
、关注
,一键三连!!!