系统整理Python的条件语句和常用方法

Python 的条件语句(if 语句)是控制程序流程的基础之一,结构清晰、语法简洁,非常适合初学者掌握。

一、基本语法结构

python 复制代码
if 条件:
    执行代码块1
elif 条件2:
    执行代码块2
else:
    执行代码块3

示例:

python 复制代码
score = 85

if score >= 90:
    print("优秀")
elif score >= 60:
    print("及格")
else:
    print("不及格")

二、条件表达式的写法(支持各种比较)

表达式 含义
a == b 等于
a != b 不等于
a > b, a < b 大于 / 小于
a >= b, a <= b 大于等于 / 小于等于
a in list a 是否在列表中
a not in list a 不在列表中
x is y, x is not y 判断对象是否相同(同一地址)
bool(变量) 判断变量是否为真(非空、非0等)

三、简洁写法:单行 if 和三元表达式

1. 单行 if:

python 复制代码
x = 10
if x > 5: print("大于5")

2. 三元表达式(类似 Java 的 ? :):

python 复制代码
result = "及格" if score >= 60 else "不及格"

四、逻辑运算符(可组合条件)

关键字 说明
and 且,两个条件都为真
or 或,只要一个为真即可
not 非,逻辑取反

示例:

python 复制代码
age = 20
gender = "male"

if age > 18 and gender == "male":
    print("成年男性")

五、常用技巧

1. 判断多个值

python 复制代码
if fruit in ("apple", "banana", "orange"):
    print("是常见水果")

2. 空值判断(None、空字符串、空列表等)

python 复制代码
name = ""
if not name:
    print("名字不能为空")

3. 使用 match(Python 3.10+ 新增结构化匹配)

python 复制代码
command = "start"

match command:
    case "start":
        print("启动中")
    case "stop":
        print("停止中")
    case _:
        print("未知命令")

六、布尔类型与隐式转换

在条件判断中,以下值会被视为 False:

  • None
  • False
  • 0、0.0
  • 空字符串 ""
  • 空列表 []、空元组 ()、空字典 {}、空集合 set()
python 复制代码
if not []:
    print("这是个空列表")  # 会执行

七、嵌套条件判断

python 复制代码
if score >= 60:
    if score >= 90:
        print("优秀")
    else:
        print("及格")
else:
    print("不及格")