Skip to main content

条件判断

程序里经常需要做选择:如果满足某个条件就执行 A,否则执行 B。Python 用 ifelifelse 来实现这种逻辑分支。

if 语句

最简单的条件判断:

teams = ["前端", "后端", "设计", "算法"]
for team in teams:
if team == "后端":
print(team.upper())
else:
print(team.title())

输出:

前端
后端
设计
算法

条件表达式

条件判断的核心是条件表达式,结果只有 TrueFalse

相等判断

skill = "Python"
print(skill == "Python") # True
print(skill == "Rust") # False

判断字符串时区分大小写:

skill = "Python"
print(skill == "python") # False
print(skill.lower() == "python") # True

不相等判断

selected = "PyTorch"
if selected != "TensorFlow":
print("用的不是 TensorFlow")

数值比较

age = 20
print(age == 20) # True
print(age != 18) # True
print(age > 18) # True
print(age >= 20) # True
print(age < 25) # True

多条件判断

and 连接多个条件,全部满足才为 True

score = 85
attendance = 90
if score >= 60 and attendance >= 80:
print("考核通过")

or 连接,满足任意一个即为 True

skill = "Python"
if skill == "Python" or skill == "Rust":
print("符合技术栈要求")

可以用括号让条件更清晰:

if (score >= 60) and (attendance >= 80):
print("考核通过")

检查列表中的元素

判断某个值是否在列表里:

skills = ["Python", "Rust", "Go"]
print("Python" in skills) # True
print("Java" in skills) # False

判断不在列表里:

if "C++" not in skills:
print("还没人报 C++")

if-elif-else 结构

多个条件分支时,用 elif(else if 的缩写):

score = 78

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}")

elif 可以有很多个,else 是最后的兜底,也可以不写。

条件语句的代码风格

  • if 后面加冒号 :
  • 条件为 True 时执行的代码必须缩进(4 个空格)
  • 比较运算符两边加空格:a == b 而不是 a==b
# 好的写法
if age >= 18:
print("成年")

# 不好的写法
if age>=18:
print("成年")