Skip to content

条件语句(if-else)

让程序做决策 —— 根据条件执行不同代码


什么是条件语句?

条件语句让程序根据不同情况执行不同代码,类似于:

  • Stata: if 条件筛选
  • R: if-else 语句
  • 日常生活: "如果下雨就带伞,否则不带"

基本语法:if 语句

1. 简单 if

python
age = 20

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

# 输出:
# 你是成年人
# 可以投票

语法要点

  • if 后面跟条件,以冒号 : 结尾
  • 缩进(4个空格或1个Tab)表示代码块
  • 缩进的代码只在条件为真时执行

对比 Stata/R

stata
* Stata (没有真正的 if 语句,只有条件筛选)
gen adult = "是成年人" if age >= 18
r
# R
if (age >= 18) {
  print("你是成年人")
  print("可以投票")
}

2. if-else(二选一)

python
age = 16

if age >= 18:
    print("你是成年人")
else:
    print("你是未成年人")

# 输出: 你是未成年人

实战示例:收入分类

python
income = 75000

if income >= 100000:
    category = "高收入"
else:
    category = "中低收入"

print(f"收入分类: {category}")
# 输出: 收入分类: 中低收入

3. if-elif-else(多条件)

python
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

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

注意

  • elif 是 "else if" 的缩写
  • 条件从上到下检查,一旦满足就停止
  • else 是可选的(兜底情况)

对比:Stata vs R vs Python

Stata 方式(生成分类变量)

stata
* Stata
gen income_group = ""
replace income_group = "低收入" if income < 30000
replace income_group = "中收入" if income >= 30000 & income < 80000
replace income_group = "高收入" if income >= 80000

R 方式

r
# R
if (income < 30000) {
  income_group <- "低收入"
} else if (income < 80000) {
  income_group <- "中收入"
} else {
  income_group <- "高收入"
}

Python 方式

python
# Python
if income < 30000:
    income_group = "低收入"
elif income < 80000:
    income_group = "中收入"
else:
    income_group = "高收入"

实战案例

案例 1:问卷数据验证

python
# 受访者数据
age = 25
income = 50000
education_years = 16

# 数据验证
print("=== 数据质量检查 ===")

# 检查年龄
if age < 0 or age > 120:
    print(" 年龄数据异常")
elif age < 18:
    print("️  未成年受访者")
else:
    print(" 年龄数据正常")

# 检查收入
if income < 0:
    print(" 收入数据异常(负数)")
elif income == 0:
    print("️  收入为零,可能失业")
elif income > 1000000:
    print("️  收入过高,需核实")
else:
    print(" 收入数据正常")

# 检查教育年限
if education_years < 0 or education_years > 30:
    print(" 教育年限异常")
else:
    print(" 教育年限正常")

案例 2:BMI 健康评估

python
# 计算 BMI
height_m = 1.75
weight_kg = 70
bmi = weight_kg / (height_m ** 2)

# BMI 分类与建议
print(f"你的 BMI: {bmi:.2f}")

if bmi < 18.5:
    category = "偏瘦"
    advice = "建议增加营养摄入"
elif bmi < 25:
    category = "正常"
    advice = "保持当前状态"
elif bmi < 30:
    category = "超重"
    advice = "建议适量运动和控制饮食"
else:
    category = "肥胖"
    advice = "建议咨询医生,制定减重计划"

print(f"分类: {category}")
print(f"建议: {advice}")

输出

你的 BMI: 22.86
分类: 正常
保持当前状态

案例 3:学术表现评估

python
# 学生数据
gpa = 3.7
attendance_rate = 0.95
assignments_completed = 18
total_assignments = 20

# 综合评估
print("=== 学术表现评估 ===")

# GPA 评估
if gpa >= 3.5:
    gpa_level = "优秀"
elif gpa >= 3.0:
    gpa_level = "良好"
elif gpa >= 2.5:
    gpa_level = "中等"
else:
    gpa_level = "需要改进"

# 出勤率评估
if attendance_rate >= 0.9:
    attendance_level = "优秀"
elif attendance_rate >= 0.75:
    attendance_level = "良好"
else:
    attendance_level = "需要改进"

# 作业完成率
completion_rate = assignments_completed / total_assignments
if completion_rate >= 0.9:
    assignment_level = "优秀"
elif completion_rate >= 0.75:
    assignment_level = "良好"
else:
    assignment_level = "需要改进"

# 总体评价
if gpa_level == "优秀" and attendance_level == "优秀" and assignment_level == "优秀":
    overall = " 优秀学生"
elif gpa_level == "需要改进" or attendance_level == "需要改进":
    overall = "️  需要辅导"
else:
    overall = " 合格学生"

print(f"GPA: {gpa} ({gpa_level})")
print(f"出勤率: {attendance_rate*100:.1f}% ({attendance_level})")
print(f"作业完成率: {completion_rate*100:.1f}% ({assignment_level})")
print(f"总体评价: {overall}")

嵌套条件语句

条件语句可以嵌套(在 if 内部再有 if)。

python
age = 25
income = 75000
has_degree = True

# 嵌套条件
if age >= 18:
    if has_degree:
        if income >= 50000:
            eligibility = "完全符合"
        else:
            eligibility = "符合但收入偏低"
    else:
        eligibility = "符合但需要学历"
else:
    eligibility = "年龄不符"

print(f"贷款资格: {eligibility}")
# 输出: 贷款资格: 完全符合

更好的写法(避免过度嵌套)

python
age = 25
income = 75000
has_degree = True

# 用逻辑运算符简化
if age >= 18 and has_degree and income >= 50000:
    eligibility = "完全符合"
elif age < 18:
    eligibility = "年龄不符"
elif not has_degree:
    eligibility = "需要学历"
elif income < 50000:
    eligibility = "收入不符"
else:
    eligibility = "未知情况"

print(f"贷款资格: {eligibility}")

条件表达式(三元运算符)

对于简单的 if-else,可以用一行代码:

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

# 条件表达式(一行)
age = 20
status = "成年人" if age >= 18 else "未成年人"

print(status)  # 成年人

语法

python
value_if_true if condition else value_if_false

实用示例

python
# 收入分类
income = 120000
category = "高收入" if income >= 100000 else "中低收入"

# 及格判断
score = 85
result = "及格" if score >= 60 else "不及格"

# 性别编码
gender = "Male"
gender_code = 1 if gender == "Male" else 0

print(category, result, gender_code)
# 输出: 高收入 及格 1

多条件判断技巧

1. 使用 in 简化多个 or

python
#  繁琐写法
major = "Economics"
if major == "Economics" or major == "Finance" or major == "Business":
    print("商科专业")

#  简洁写法
major = "Economics"
if major in ["Economics", "Finance", "Business"]:
    print("商科专业")

2. 使用范围判断

python
# 检查年龄是否在合理范围
age = 25

#  Python 支持链式比较
if 18 <= age <= 65:
    print("工作年龄人口")

# 等价于(但不推荐)
if age >= 18 and age <= 65:
    print("工作年龄人口")

3. 提前返回(在函数中)

python
def check_eligibility(age, income, has_job):
    # 提前返回不符合的情况
    if age < 18:
        return "年龄不符"

    if income < 30000:
        return "收入不符"

    if not has_job:
        return "需要有工作"

    # 所有条件都满足
    return "符合条件"

result = check_eligibility(25, 50000, True)
print(result)  # 符合条件

常见错误

错误 1:忘记冒号

python
if age >= 18  #  SyntaxError: 缺少冒号
    print("成年人")

if age >= 18:  # 
    print("成年人")

错误 2:缩进错误

python
#  缩进不一致
if age >= 18:
    print("成年人")
  print("可以投票")  # IndentationError

#  缩进一致
if age >= 18:
    print("成年人")
    print("可以投票")

错误 3:使用赋值而不是比较

python
age = 18
if age = 18:  #  SyntaxError: 应该用 ==
    print("刚好18岁")

if age == 18:  # 
    print("刚好18岁")

错误 4:空 if 块

python
if age >= 18:
    #  SyntaxError: 不能为空

if age >= 18:
    pass  #  用 pass 占位

完整实战:问卷数据处理

python
# === 问卷数据 ===
respondent_id = 1001
age = 35
gender = "Female"
education = "Master's Degree"
employment_status = "Employed"
annual_income = 85000
marital_status = "Married"
num_children = 2

# === 数据验证与分类 ===

print(f"=== 受访者 {respondent_id} 数据报告 ===\n")

# 1. 年龄组
if age < 25:
    age_group = "青年(<25)"
elif age < 45:
    age_group = "中青年(25-44)"
elif age < 65:
    age_group = "中老年(45-64)"
else:
    age_group = "老年(65+)"

print(f"年龄组: {age_group}")

# 2. 教育水平编码
education_levels = {
    "High School": 1,
    "Associate Degree": 2,
    "Bachelor's Degree": 3,
    "Master's Degree": 4,
    "Doctoral Degree": 5
}

if education in education_levels:
    education_code = education_levels[education]
    if education_code >= 4:
        education_category = "高学历"
    elif education_code >= 3:
        education_category = "本科"
    else:
        education_category = "专科及以下"
else:
    education_code = 0
    education_category = "未知"

print(f"教育水平: {education} ({education_category})")

# 3. 收入分组
if annual_income < 30000:
    income_quartile = "Q1(低收入)"
elif annual_income < 60000:
    income_quartile = "Q2(中低收入)"
elif annual_income < 100000:
    income_quartile = "Q3(中高收入)"
else:
    income_quartile = "Q4(高收入)"

print(f"收入分组: ${annual_income:,} ({income_quartile})")

# 4. 家庭结构
if marital_status == "Married" and num_children > 0:
    family_type = "已婚有子女"
elif marital_status == "Married":
    family_type = "已婚无子女"
elif num_children > 0:
    family_type = "单亲家庭"
else:
    family_type = "单身"

print(f"家庭结构: {family_type}")

# 5. 目标人群判断(示例:高学历高收入中青年)
is_target_demographic = (
    (age_group == "中青年(25-44)") and
    (education_category == "高学历") and
    (income_quartile in ["Q3(中高收入)", "Q4(高收入)"])
)

if is_target_demographic:
    print("\n 符合目标人群特征")
else:
    print("\n 不符合目标人群特征")

练习题

练习 1:税率计算

python
# 根据收入计算税率
income = 75000

# 税率表:
# 0-50000: 10%
# 50001-100000: 20%
# 100001+: 30%

# 计算应缴税额并输出

练习 2:学生奖学金评定

python
gpa = 3.8
volunteer_hours = 50
research_papers = 2

# 奖学金规则:
# - 一等奖学金:GPA >= 3.8 且 (志愿时长 >= 40 或 论文 >= 2)
# - 二等奖学金:GPA >= 3.5
# - 三等奖学金:GPA >= 3.0
# - 无奖学金:其他情况

# 判断奖学金等级

练习 3:健康风险评估

python
age = 55
bmi = 28
smoking = True
exercise_days_per_week = 1
family_history = True  # 家族病史

# 风险评分规则:
# - 年龄 > 50: +2 分
# - BMI >= 25: +2 分
# - 吸烟: +3 分
# - 运动天数 < 3: +1 分
# - 有家族病史: +2 分

# 计算总分并给出风险等级:
# 0-2: 低风险
# 3-5: 中风险
# 6+: 高风险

下一步

在下一节中,我们将学习 循环(for/while),让程序重复执行任务。

继续加油!

基于 MIT 许可证发布。内容版权归作者所有。