Python3 条件控制

if / elif / else 分支、if 嵌套与 match...case 模式匹配。

Beginner
Key PointsPython 用缩进划分代码块,条件后必须跟冒号;多分支用 elif,3.10+ 可用 match...case 做结构化匹配。

if 语句

Python marks blocks with a colon plus indentation, not parentheses. The indented block runs when the condition is true; otherwise else runs. Chains use elif, evaluated top-down with the first match winning.

Python
age = 20

if age >= 18:
    print("adult")
else:
    print("minor")

score = 85
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 60:
    grade = 'C'
else:
    grade = 'D'

print("grade:", grade)
Output
adult
grade: B

if 嵌套

An if block may contain another if. Deep nesting hurts readability — merge conditions with and or return early to flatten it.

Python
num = 12

if num % 2 == 0:
    if num % 3 == 0:
        print(num, "divisible by 6")
    else:
        print(num, "even but not divisible by 3")
else:
    print(num, "odd")

# 扁平化写法
if num % 2 == 0 and num % 3 == 0:
    print(num, "divisible by 6")
Output
12 divisible by 6
12 divisible by 6

match...case

Python 3.10 adds match...case, which matches patterns rather than comparing values. | means "or", case _ is the catch-all, and sequence/mapping/class patterns can destructure data.

Python
def http_status(code):
    match code:
        case 200:
            return "OK"
        case 301 | 302:
            return "Redirect"
        case 404:
            return "Not Found"
        case _:
            return "Unknown"

for c in (200, 302, 404, 500):
    print(c, http_status(c))

def describe(point):
    match point:
        case (0, 0):
            return "origin"
        case (x, 0):
            return f"on x-axis at {x}"
        case (0, y):
            return f"on y-axis at {y}"
        case (x, y):
            return f"at {x},{y}"

print(describe((0, 0)), describe((5, 0)), describe((0, 7)), describe((2, 3)))
Output
200 OK
302 Redirect
404 Not Found
500 Unknown
origin on x-axis at 5 on y-axis at 7 at 2,3
match is not switch: case 200 matches a *pattern*, so case some_name captures anything. Use literals or ALL_CAPS names to compare against constants.

Friends & Partners