← 返回首页
🔀

条件语句

📂 python ⏱ 2 min 385 words

if语句基础

条件语句让程序根据条件执行不同的代码块。Python使用 ifelifelse 关键字:

age = 20

if age >= 18:
    print("你已成年")
    print("可以投票了")

注意:Python使用缩进(通常4个空格)来定义代码块,而不是花括号。

if-else结构

temperature = 35

if temperature > 30:
    print("天气很热")
else:
    print("天气不热")

if-elif-else结构

多个条件判断时使用 elif

score = 85

if score >= 90:
    grade = "优秀"
elif score >= 80:
    grade = "良好"
elif score >= 70:
    grade = "中等"
elif score >= 60:
    grade = "及格"
else:
    grade = "不及格"

print(f"成绩等级: {grade}")  # 输出: 成绩等级: 良好

嵌套if语句

条件语句可以嵌套使用:

age = 25
has_id = True

if age >= 18:
    if has_id:
        print("允许进入")
    else:
        print("请出示身份证")
else:
    print("未成年人禁止进入")

建议:避免过深的嵌套(超过3层),可以通过提前返回或使用逻辑运算符简化。

三元表达式

Python的三元表达式(条件表达式)提供了简洁的写法:

age = 20

# 传统写法
if age >= 18:
    status = "成年"
else:
    status = "未成年"

# 三元表达式
status = "成年" if age >= 18 else "未成年"

print(status)  # 输出: 成年

条件表达式的真值判断

Python中很多值可以直接用于条件判断,称为"真值测试":

# 以下值被视为False
if not None:
    print("None为假")
if not 0:
    print("0为假")
if not "":
    print("空字符串为假")
if not []:
    print("空列表为假")
if not {}:
    print("空字典为假")
if not set():
    print("空集合为假")

# 以下值被视为True
if True:
    print("True为真")
if 1:
    print("非零数字为真")
if "hello":
    print("非空字符串为真")
if [1, 2, 3]:
    print("非空列表为真")

多条件组合

使用 andornot 组合多个条件:

age = 25
income = 10000
has_house = False

# 检查贷款资格
if age >= 18 and income >= 5000:
    print("基本条件满足")

if income >= 20000 or has_house:
    print("优质客户")

if not has_house:
    print("没有房产,可能需要更高首付")

实用示例

简易计算器

num1 = 10
num2 = 3
operator = "+"

if operator == "+":
    result = num1 + num2
elif operator == "-":
    result = num1 - num2
elif operator == "*":
    result = num1 * num2
elif operator == "/":
    if num2 != 0:
        result = num1 / num2
    else:
        result = "错误:除数不能为零"
else:
    result = "不支持的运算符"

print(f"{num1} {operator} {num2} = {result}")

季节判断

month = 7

if month in (3, 4, 5):
    season = "春季"
elif month in (6, 7, 8):
    season = "夏季"
elif month in (9, 10, 11):
    season = "秋季"
elif month in (12, 1, 2):
    season = "冬季"
else:
    season = "无效月份"

print(f"{month}月是{season}")

用户权限检查

role = "admin"
is_active = True

if role == "admin":
    print("管理员权限:可以访问所有功能")
elif role == "editor" and is_active:
    print("编辑权限:可以编辑内容")
elif role == "viewer":
    print("查看权限:只能查看内容")
elif not is_active:
    print("账号已禁用,请联系管理员")
else:
    print("未知角色")

避免常见错误

# 错误:比较多个值时不要使用链式比较(Python支持,但要注意)
x = 5
# if 1 < x < 10:  # 正确,Python支持
#     print("在范围内")

# 错误:赋值和比较不要混淆
# if x = 5:  # 语法错误!
# if x == 5: # 正确

# 正确:与None比较时使用is
value = None
if value is None:   # 推荐
    print("值为空")
if value == None:   # 不推荐
    print("值为空")

总结

条件语句是程序逻辑的核心。掌握 if-elif-else 结构和三元表达式后,你就能编写具有决策能力的程序。下一节我们将学习循环结构,让程序能够重复执行任务。