Python 中的 if else:条件语句指南

通过清晰的示例掌握 Python if else 语句。学习语法、最佳实践和常见用例。包含交互式代码示例和教程。

Python 中的 if else 语句通过在执行条件为真时执行一个代码块,在条件为假时执行另一个代码块,提供双向决策。与简单的 if 语句在条件为假时不执行任何操作不同,if else 确保两个代码路径之一将始终执行。这对于创建需要处理成功和失败场景的程序至关重要。

基本 if else 语法

if else 语句通过在条件评估为 False 时添加替代操作来扩展基本的 if 语句。

if condition:
    # code to execute if condition is True
    statement1
else:
    # code to execute if condition is False
    statement2

else 关键字捕获未被 if 条件捕获的任何内容,作为 if 语句未涵盖场景的"捕获所有"。Python 在 ifelse 关键字后使用冒号 (:),后跟缩进的代码块。

示例 1:简单的 if else 语句

a = 200
b = 33

if b > a:
    print("b is greater than a")
else:
    print("b is not greater than a")
输出:
b is not greater than a

Since 33 is not greater than 200, the condition is false, so the else block executes.

if else 的工作原理

if else 语句遵循简单的执行流程:

  1. Python 评估 if 关键字后的条件
  2. 如果条件为 True,则执行第一个缩进块并跳过 else
  3. 如果条件为 False,则跳过第一个块并执行 else
  4. 任一块完成后,执行继续执行整个 if else 结构之后的代码

示例:温度检查

temperature = 15

if temperature > 20:
    print("It's warm outside")
else:
    print("It's cool outside")

print("Have a nice day!")
输出:
It's cool outside
Have a nice day!

无论采用哪个分支,最后的 print 语句都会执行。

使用 if else 比较值

if else 语句通常使用比较运算符根据数值或字符串值做出决策。

示例 1:数字比较

number = 7

if number % 2 == 0:
    print("The number is even")
else:
    print("The number is odd")
输出:
The number is odd

示例 2:字符串比较

username = "admin"

if username == "admin":
    print("Welcome, Administrator!")
else:
    print("Welcome, User!")
输出:
Welcome, Administrator!

示例 3:年龄验证

age = 16

if age >= 18:
    print("You are eligible to vote")
else:
    print("You are not eligible to vote yet")
输出:
You are not eligible to vote yet

if else 块中的多个语句

ifelse 块都可以包含多个语句,只要它们保持一致的缩进。

示例:

score = 85

if score >= 90:
    print("Excellent performance!")
    print("You earned an A grade")
    grade = "A"
    bonus_points = 10
else:
    print("Good effort!")
    print("Keep working hard")
    grade = "B"
    bonus_points = 5

print(f"Your grade is: {grade}")
print(f"Bonus points: {bonus_points}")
输出:
Good effort!
Keep working hard
Your grade is: B
Bonus points: 5

单行 if else(三元运算符)

对于带有单个语句的简单条件,Python 允许您在一行上编写 if else,创建更简洁的代码。

标准格式:

age = 20

if age >= 18:
    status = "adult"
else:
    status = "minor"

print(status)

单行格式(三元运算符):

age = 20
status = "adult" if age >= 18 else "minor"
print(status)
输出:
adult

More Examples:

# Example 1: Maximum of two numbers
a = 10
b = 20
max_value = a if a > b else b
print(f"Maximum: {max_value}")  # Output: Maximum: 20

# Example 2: Pass/Fail determination
marks = 75
result = "Pass" if marks >= 50 else "Fail"
print(result)  # Output: Pass

# Example 3: Sign determination
number = -5
sign = "Positive" if number > 0 else "Non-positive"
print(sign)  # Output: Non-positive

这种紧凑的语法对于简单的赋值和快速条件特别有用。

使用逻辑运算符组合条件

您可以使用 andornot 运算符在 if else 语句中创建复杂条件。

示例 1:使用 and 运算符

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive")
else:
    print("You cannot drive")
输出:
You can drive

示例 2:使用 or 运算符

day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")
else:
    print("It's a weekday")
输出:
It's the weekend!

示例 3:使用 not 运算符

is_raining = False

if not is_raining:
    print("You don't need an umbrella")
else:
    print("Take an umbrella")
输出:
You don't need an umbrella

示例 4:温度范围检查

temperature = 35

if temperature > 30 and temperature < 40:
    print("It's a hot day!")
else:
    print("Temperature is moderate")
输出:
It's a hot day!

嵌套 if else 语句

您可以将 if else 语句放在其他 if else 语句内部,以处理多个决策级别。

示例 1:基本嵌套

number = 10

if number >= 0:
    if number == 0:
        print("Number is zero")
    else:
        print("Number is positive")
else:
    print("Number is negative")
输出:
Number is positive

示例 2:带嵌套的成绩分类

marks = 85

if marks >= 50:
    print("You passed!")
    if marks >= 90:
        print("Grade: A - Excellent!")
    else:
        print("Grade: B - Good job!")
else:
    print("You failed")
    print("Please retake the exam")
输出:
You passed!
Grade: B - Good job!

示例 3:多级用户认证

username = "admin"
password = "secret123"

if username == "admin":
    if password == "secret123":
        print("Access granted")
        print("Welcome to admin panel")
    else:
        print("Incorrect password")
else:
    print("User not found")
输出:
Access granted
Welcome to admin panel

虽然嵌套功能强大,但过度嵌套会使代码更难阅读——考虑使用 elif 来实现更清晰的多条件逻辑。

使用 if else 验证用户输入

if else 语句对于输入验证和错误处理至关重要。

示例 1:空字符串检查

username = ""

if len(username) > 0:
    print(f"Welcome, {username}!")
else:
    print("Error: Username cannot be empty")
输出:
Error: Username cannot be empty

示例 2:密码长度验证

password = "abc"

if len(password) >= 8:
    print("Password is valid")
else:
    print("Password must be at least 8 characters")
输出:
Password must be at least 8 characters

示例 3:数字范围验证

age = 150

if age > 0 and age <= 120:
    print(f"Age {age} is valid")
else:
    print("Invalid age entered")
输出:
Invalid age entered

示例 4:列表成员资格检查

allowed_users = ["alice", "bob", "charlie"]
current_user = "david"

if current_user in allowed_users:
    print("Access granted")
else:
    print("Access denied")
输出:
Access denied

使用 elif 扩展

虽然本页重点介绍 if else,但您可以在 ifelse 之间添加 elif(else if)来顺序测试多个条件。

temperature = 22

if temperature > 30:
    print("It's hot outside!")
elif temperature > 20:
    print("It's warm outside")
elif temperature > 10:
    print("It's cool outside")
else:
    print("It's cold outside!")
输出:
It's warm outside

else 语句必须放在最后,并在没有其他条件为真时作为默认值。

常见用例

用例 1:登录系统

stored_password = "python123"
entered_password = "python123"

if entered_password == stored_password:
    print("Login successful")
else:
    print("Invalid password")
输出:
Login successful

用例 2:折扣计算器

purchase_amount = 120

if purchase_amount >= 100:
    discount = purchase_amount * 0.10
    print(f"You get a 10% discount: ${discount}")
else:
    print("No discount available")
输出:
You get a 10% discount: $12.0

用例 3:通过/失败系统

exam_score = 45
passing_score = 50

if exam_score >= passing_score:
    print("Congratulations! You passed")
else:
    print(f"Sorry, you need {passing_score - exam_score} more points to pass")
输出:
Sorry, you need 5 more points to pass

用例 4:文件扩展名检查器

filename = "document.pdf"

if filename.endswith(".pdf"):
    print("This is a PDF file")
else:
    print("This is not a PDF file")
输出:
This is a PDF file

用例 5:闰年检查器

year = 2024

if year % 4 == 0:
    print(f"{year} is a leap year")
else:
    print(f"{year} is not a leap year")
输出:
2024 is a leap year

要避免的常见错误

错误 1:缺少冒号

# Wrong
if number > 0
    print("Positive")
else
    print("Not positive")

# Correct
if number > 0:
    print("Positive")
else:
    print("Not positive")

错误 2:缩进不一致

# Wrong
if age >= 18:
    print("Adult")
else:
  print("Minor")  # Different indentation

# Correct
if age >= 18:
    print("Adult")
else:
    print("Minor")

错误 3:在 else 后使用 elif

# Wrong
if x > 0:
    print("Positive")
else:
    print("Not positive")
elif x < 0:  # SyntaxError
    print("Negative")

# Correct
if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")

错误 4:空代码块

# Wrong
if condition:
    # Code here
else:
    # This will cause an error

# Correct - use pass for placeholder
if condition:
    print("Condition met")
else:
    pass  # Do nothing

使用 pass 作为占位符

最佳实践

实践 1:保持条件简单易读

# Less readable
if not (age < 18 or not has_permission):
    print("Allowed")

# More readable
if age >= 18 and has_permission:
    print("Allowed")

实践 2:使用有意义的变量名

# Poor
if x > 100:
    y = True

# Better
if purchase_amount > 100:
    eligible_for_discount = True

实践 3:明确处理两个路径

# When both outcomes matter, use if else
file_exists = True

if file_exists:
    print("Loading file...")
else:
    print("Creating new file...")

当两个结果都很重要时,使用 if else

实践 4:避免深度嵌套

# Harder to read
if condition1:
    if condition2:
        if condition3:
            action()

# Better - use elif or logical operators
if condition1 and condition2 and condition3:
    action()

亲自尝试

尝试使用 if else 语句

就绪
main.py
输出控制台 0 ms
// 点击"运行代码"查看结果

相关主题

常见问题

Python 中 ifif else 有什么区别?

if 语句仅在条件为真时执行代码,否则不执行任何操作。if else 语句保证两个代码块之一将执行——当条件为真时执行 if 块,当条件为假时执行 else 块。

我可以有一个不带 elif 的 if else 吗?

可以,if else 在没有 elif 的情况下完全可以正常工作。elif 关键字仅在您想顺序测试多个条件时才需要。

在 Python if else 语句中,我需要在条件周围使用括号吗?

不需要,括号是可选的。if (x > 5):if x > 5: 都是有效的,尽管后者在 Python 中更常用。

我可以在一行中使用 if else 吗?

可以,Python 支持三元运算符:result = "yes" if condition else "no"。这对于简单的赋值很有用。

如果我忘记在 else 块中缩进代码会发生什么?

Python 会引发 IndentationError,因为它需要一致的缩进来定义代码块。

else 可以单独出现而不带 if 吗?

不可以,else 必须始终与前面的 if 语句配对。您不能独立使用 else