px普贤教程PuXian
普贤教程 › 基础教程

条件控制

条件控制只有三个关键字:if、elif、else。语法简单,但真值判断规则和缩进细节值得先弄清楚。

基本形式

px
def grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 60:
        return "C"
    else:
        return "D"

print(grade(95))
print(grade(85))
print(grade(61))
print(grade(20))
text
A
B
C
D

条件是任意表达式,只要结果是 bool 或能当布尔用。分支必须缩进一级,冒号不能省。

真值规则

以下值在条件里等价于 false:

值真假
true真
false假
0 / 0.0假
非零数字真
"" 空串假
非空字符串真
[] 空列表假
null假
px
if 1:
    print("非零为真")
if not 0:
    print("0 为假")
if not "":
    print("空串为假")
if not []:
    print("空列表为假")
text
非零为真
0 为假
空串为假
空列表为假
空字典不一定是假不要依赖 if d: 判断字典是否为空,显式写 len(d.keys()) > 0。这条在排查"为什么分支没进去"时能省很多时间。

组合条件

px
def can_access(user):
    if user.has("role") and user["role"] == "admin":
        return true
    if user.has("vip") and user["vip"]:
        return true
    return false

print(str(can_access({"role": "admin"})))
print(str(can_access({"vip": true})))
print(str(can_access({"role": "user"})))
text
true
true
false

嵌套

px
def describe(n):
    if n > 0:
        if n % 2 == 0:
            return "正偶数"
        else:
            return "正奇数"
    elif n < 0:
        return "负数"
    return "零"

print(describe(4))
print(describe(5))
print(describe(-1))
print(describe(0))
text
正偶数
正奇数
负数
零

嵌套超过两层时,改用「提前返回」的写法会更清楚:

px
def describe2(n):
    if n == 0:
        return "零"
    if n < 0:
        return "负数"
    if n % 2 == 0:
        return "正偶数"
    return "正奇数"

print(describe2(4))
text
正偶数

用字典代替长分支

分支是"查表"而不是"判断"时,用字典更直观:

px
let OK = {200: "成功", 201: "已创建", 204: "无内容"}
let ERR = {400: "参数错误", 401: "未登录", 404: "不存在"}

def status_text(code):
    if OK.has(code):
        return OK[code]
    if ERR.has(code):
        return ERR[code]
    return "未知状态"

print(status_text(200))
print(status_text(404))
print(status_text(500))
text
成功
不存在
未知状态

常见错误

写法报错
if x > 1 { }E2001:花括号不是代码块
if x > 1(漏冒号)E2001 语法错误
else ifE2001:应该是 elif
分支体不缩进E2001:期望缩进