苦练Python第7天:布尔七日斩

288 阅读2分钟

苦练Python第7天:布尔七日斩

原文链接:dev.to/therahul_gu…
作者:Rahul Gupta
译者:倔强青铜三

前言

大家好,我是倔强青铜三。是一名热情的软件工程师,我热衷于分享和传播IT技术,致力于通过我的知识和技能推动技术交流与创新,欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!

欢迎来到 100天Python挑战 第7天!
今天我们要让代码学会“自己思考”——用布尔值和逻辑运算符做出判断。掌握它们,if语句才能真正活起来。


📦 今日速览

  • 布尔类型:TrueFalse
  • 比较运算符速查
  • 逻辑运算符:andornot
  • 组合条件与实战案例
  • 真假值的隐式规则

✅ 什么是布尔值?

布尔(Boolean)只有两位居民:

True
False

大小写敏感,true 会报错。可直接赋给变量:

is_sunny = True
is_raining = False

🧠 返回布尔值的比较

Python 表达式天生会“判官”:

x = 5
print(x > 3)    # True
print(x == 10)  # False
print(x != 7)   # True

常用比较运算符

运算符含义示例结果
==等于5 == 5True
!=不等于3 != 2True
>大于4 > 2True
<小于5 < 3False
>=大于等于5 >= 5True
<=小于等于2 <= 1False

🔗 逻辑运算符三连招

1️⃣ and——所有条件为真才为真

age = 20
is_student = True
print(age > 18 and is_student)  # True

2️⃣ or——任一条件为真即为真

print(age > 18 or is_student == False)  # True

3️⃣ not——真假颠倒

print(not is_student)  # False

🔍 实战:折扣判定

age = 16
has_coupon = True

if age < 18 or has_coupon:
    print("You get a discount!")
else:
    print("Sorry, no discount.")

输出:

You get a discount!

🧪 彩蛋:真假值的隐式规则

Python 把下列值视为 False

  • 空字符串 ""
  • 00.0
  • 空容器 [] {} set()
  • None

其余皆为 True

print(bool(""))   # False
print(bool("Hi")) # True
print(bool(0))    # False
print(bool(42))   # True

利用这一特性可以精简代码:

name = ""
if not name:
    print("Please enter your name.")

🚀 今日复盘

  • 认识 TrueFalse
  • 掌握比较运算符
  • andornot 组合条件
  • if 中写出更智能的判断
  • 利用隐式真假值写更简洁的代码

最后感谢阅读!欢迎关注我,微信公众号倔强青铜三。欢迎点赞收藏关注,一键三连!!!