Python if-else 不是只能写分支——这些高阶用法你可能不知道

有个朋友写了这么一段:

if user["role"] == "admin":
    can_edit = True
else:
    can_edit = False

我问他知道三元表达式吗。他说知道,但是不敢用,怕写错了。

今天把条件判断从基础到骚操作全讲一遍。保证看完你再也不怕写 if

基础语法:缩进就是一切

score = 85

if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 60:
    print("及格")
else:
    print("不及格")
# 输出:良好

几个关键点:

  • elif 可以有 0 个或多个
  • else 可有可无
  • 条件后面必须加冒号
  • 缩进必须一致(4 个空格,别混 Tab)

比较运算符

a == b   # 等于
a != b   # 不等于
a > b    # 大于
a < b    # 小于
a >= b   # 大于等于
a <= b   # 小于等于
a is b   # 是同一个对象(比地址)
a is not b
a in b   # a 是 b 的成员
a not in b

is== 的区别:is 比的是对象身份(内存地址),== 比的是值。一般判断用 ==,只有和 None 比较时才用 is

if result is None:      # ✅
if result == None:      # 也行但不够 Pythonic

逻辑运算符

# and:两边都为 True 才 True
if age >= 18 and has_id:
    print("可以进入")

# or:一边为 True 就 True
if vip or score > 80:
    print("免排队")

# not:取反
if not is_banned:
    print("允许访问")

短路特性很重要:

# and:左边 False 就不看右边
False and 会报错的代码  # 不会报错,右边被跳过了

# or:左边 True 就不看右边
True or 会报错的代码   # 不会报错

这个特性经常用来做安全判断:

# ✅ 如果 user 是 None,不会尝试访问 user["name"]
if user and user["name"] == "张三":
    print("找到张三")

# ❌ 如果 user 是 None,直接报错
if user["name"] == "张三":
    print("找到张三")

三元表达式:一行搞定 if-else

# 传统写法
if score >= 60:
    result = "及格"
else:
    result = "不及格"

# 三元表达式
result = "及格" if score >= 60 else "不及格"

语法:值1 if 条件 else 值2。条件为 True 取值1,False 取值2。

能用三元表达式的地方就别写四行:

can_edit = True if role == "admin" else False  # 啰嗦
can_edit = role == "admin"                      # 更简洁,因为 == 本身就返回 bool

message = "通过" if score >= 60 else "未通过"
abs_value = x if x >= 0 else -x

多条件组合

# 判断闰年
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"{year}是闰年")

# 多值匹配
role = "admin"
if role in ("admin", "superadmin", "moderator"):
    print("有管理权限")

# 范围判断(Python 特有,真香)
age = 25
if 18 <= age <= 60:
    print("工作年龄")

18 <= age <= 60 这种链式比较是 Python 的特色,其他语言得写成 age >= 18 and age <= 60

实战:成绩等级判断器

def get_grade(score):
    """输入分数,返回等级和评语"""
    if not isinstance(score, (int, float)):
        return "无效", "请输入数字"
    if score < 0 or score > 100:
        return "无效", "分数需在0-100之间"

    if score >= 90:
        return "A", "牛逼!"
    elif score >= 80:
        return "B", "不错"
    elif score >= 70:
        return "C", "还行"
    elif score >= 60:
        return "D", "勉强过关"
    else:
        return "F", "下次加油"

# 测试
scores = [95, 82, 67, 55, 105, "abc"]
for s in scores:
    grade, comment = get_grade(s)
    print(f"{s}分 → {grade}级:{comment}")

新手常见4个坑

坑1:=== 搞混

age = 18
# if age = 18:    # SyntaxError! 赋值表达式不能当条件
if age == 18:      # ✅
    print("成年")

坑2:and/or 优先级搞错

# ❌ 本意是 (a and b) or c,实际是 a and (b or c)
if a and b or c and not d:
    pass

# ✅ 加括号,意图清晰
if (a and b) or (c and not d):
    pass

坑3:空列表/空字符串的真值

items = []
if items:                    # False!空列表是假值
    print("有数据")
else:
    print("没数据")

# Python 中的假值:False, None, 0, 0.0, "", [], {}, (), set()

坑4:None 判断

# ❌ 不够 Pythonic
if x == None:
    pass

# ✅ 推荐
if x is None:
    pass

动手试试

  1. 判断一个年份是否是闰年
  2. 判断一个三角形是否合法(任意两边之和大于第三边)
  3. 做一个简易登录验证:用户名和密码都对才能进

参考答案:

# 1. 闰年
year = 2024
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(f"{year}是闰年" if is_leap else f"{year}不是闰年")

# 2. 三角形
a, b, c = 3, 4, 5
if a + b > c and a + c > b and b + c > a:
    print("可以构成三角形")
else:
    print("不能构成三角形")

# 3. 登录
username = input("用户名:")
password = input("密码:")
if username == "admin" and password == "123456":
    print("登录成功")
else:
    print("用户名或密码错误")

写在最后

条件判断看着简单,却是程序逻辑的基石。三个建议:

  1. 条件复杂时加括号,别省那几个字符
  2. 三元表达式能用就用,但别嵌套(可读性灾难)
  3. 善用 if variable: 判空,别写 if len(list) > 0:

下一篇聊循环——forwhile。循环 + 条件判断 = 能写出真正有用的程序了。

更多推荐