初面网初面网

条件判断——if / elif / else

概念讲解

程序经常需要"做选择"——根据不同的情况执行不同的操作。条件判断就是让程序做选择的机制。

if 条件1:
    # 条件1为True时执行
elif 条件2:
    # 条件1为False,条件2为True时执行
else:
    # 所有条件都为False时执行

几个关键点:

  • if 是必须的,elifelse 可选
  • 条件为 True 时进入代码块,为 False 时跳过
  • elif 是 "else if" 的缩写,可以有任意多个
  • else 是兜底,当所有条件都不满足时执行

代码示例

分级评定:学生成绩等级

def grade(score):
    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, 45, 88, 73]
for s in scores:
    print(f"{s}分 → {grade(s)}")

多条件组合:用户登录验证

def check_login(username, password, ip_blocklist):
    # 检查用户名格式
    if not username or len(username) < 3:
        return "用户名无效"
    
    # 检查IP是否被封
    if ip_blocklist and ip_blocklist.get(username) == ip_blocklist.get("current_ip"):
        return "IP已被封禁"
    
    # 检查密码正确性(假设正确密码是"secret")
    if password != "secret":
        return "密码错误"
    
    return "登录成功"

# 测试
print(check_login("alice", "secret", {}))           # 登录成功
print(check_login("al", "secret", {}))               # 用户名无效
print(check_login("alice", "wrong", {}))             # 密码错误

三元表达式:简化单行if/else

temperature = 22
weather = "暖和" if temperature > 20 else "凉爽"
print(f"今天天气{weather}")

练习题

题目:写一个函数,接收一个表示日期的字符串(格式如 "2024-03-15"),判断这是当年的第几天。

平年和闰年的规则:

  • 能被4整除但不能被100整除 → 闰年
  • 能被400整除 → 闰年
  • 其他 → 平年
参考答案
def day_of_year(date_str):
    year, month, day = map(int, date_str.split("-"))
    
    # 判断闰年
    if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
        days_in_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    else:
        days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    
    # 累加之前月份的天数
    total = sum(days_in_month[:month - 1]) + day
    return total

print(day_of_year("2024-03-15"))  # 75(2024是闰年)
print(day_of_year("2023-03-15"))  # 74(2023是平年)

关键思维:

  • 用列表存储每个月的天数,闰年2月多一天
  • sum(days_in_month[:month-1]) 累加当前月之前的所有天数
  • 把判断逻辑封装成函数,让主逻辑更清晰

更新于 2026/6/7