Skip to content

Python 条件控制

条件控制是编程中的基本概念,用于根据不同的条件执行不同的代码块。Python 提供了 ifelifelse 语句来实现条件控制。本章节将详细介绍 Python 中的条件控制语句。

if 语句

if 语句用于检查一个条件是否为真,如果为真则执行相应的代码块。

基本语法

python
if condition:
    # 条件为真时执行的代码块

示例:

python
# if 语句示例
age = 18

if age >= 18:
    print("你已经成年了!")
    print("可以投票了。")

print("程序结束。")

输出:

你已经成年了!
可以投票了。
程序结束。

if-else 语句

if-else 语句用于检查一个条件是否为真,如果为真则执行 if 代码块,否则执行 else 代码块。

基本语法

python
if condition:
    # 条件为真时执行的代码块
else:
    # 条件为假时执行的代码块

示例:

python
# if-else 语句示例
age = 16

if age >= 18:
    print("你已经成年了!")
    print("可以投票了。")
else:
    print("你还未成年。")
    print("不能投票。")

print("程序结束。")

输出:

你还未成年。
不能投票。
程序结束。

if-elif-else 语句

if-elif-else 语句用于检查多个条件,依次检查每个条件,直到找到一个为真的条件,执行相应的代码块。如果所有条件都为假,则执行 else 代码块。

基本语法

python
if condition1:
    # 条件1为真时执行的代码块
elif condition2:
    # 条件2为真时执行的代码块
elif condition3:
    # 条件3为真时执行的代码块
else:
    # 所有条件都为假时执行的代码块

示例:

python
# if-elif-else 语句示例
score = 85

if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 70:
    print("中等")
elif score >= 60:
    print("及格")
else:
    print("不及格")

print("程序结束。")

输出:

良好
程序结束。

嵌套的条件语句

可以在 ifelifelse 代码块中嵌套其他条件语句。

示例:

python
# 嵌套的条件语句示例
age = 20
has_license = True

if age >= 18:
    print("你已经成年了。")
    if has_license:
        print("你可以开车。")
    else:
        print("你需要先考驾照。")
else:
    print("你还未成年。")
    print("不能开车。")

print("程序结束。")

输出:

你已经成年了。
你可以开车。
程序结束。

条件表达式(三元运算符)

Python 提供了条件表达式(也称为三元运算符),用于在一行中简洁地表达 if-else 逻辑。

基本语法

python
value_if_true if condition else value_if_false

示例:

python
# 条件表达式示例
age = 18

message = "你已经成年了!" if age >= 18 else "你还未成年。"
print(message)

# 多个条件表达式
score = 75
grade = "优秀" if score >= 90 else "良好" if score >= 80 else "中等" if score >= 70 else "及格" if score >= 60 else "不及格"
print(grade)

# 用于赋值
x = 10
y = 20
max_value = x if x > y else y
print(f"最大值是:{max_value}")

输出:

你已经成年了!
中等
最大值是:20

逻辑运算符

在条件控制中,经常使用逻辑运算符来组合多个条件。Python 提供了三个逻辑运算符:andornot

and 运算符

and 运算符用于检查多个条件是否都为真,只有当所有条件都为真时,结果才为真。

示例:

python
# and 运算符示例
age = 20
has_license = True

if age >= 18 and has_license:
    print("你可以开车。")
else:
    print("你不能开车。")

# 多个条件
x = 5
if x > 0 and x < 10 and x % 2 == 1:
    print("x 是一个介于 0 和 10 之间的奇数。")

输出:

你可以开车。
x 是一个介于 0 和 10 之间的奇数。

or 运算符

or 运算符用于检查多个条件是否至少有一个为真,只要有一个条件为真,结果就为真。

示例:

python
# or 运算符示例
score = 55

if score >= 60 or score == 59:
    print("你及格了!")
else:
    print("你不及格。")

# 多个条件
x = 15
if x < 0 or x > 10 or x % 2 == 0:
    print("x 是负数、大于 10 或偶数。")

输出:

你不及格。
x 是负数、大于 10 或偶数。

not 运算符

not 运算符用于取反一个条件的结果,如果条件为真则返回假,如果条件为假则返回真。

示例:

python
# not 运算符示例
has_license = False

if not has_license:
    print("你没有驾照。")
else:
    print("你有驾照。")

# 与其他运算符结合使用
age = 16
if not (age >= 18):
    print("你还未成年。")

输出:

你没有驾照。
你还未成年。

成员运算符

成员运算符用于检查一个元素是否在一个序列(如列表、元组、字符串等)中。Python 提供了 innot in 运算符。

in 运算符

in 运算符用于检查一个元素是否在一个序列中,如果在则返回真,否则返回假。

示例:

python
# in 运算符示例
fruits = ["apple", "banana", "cherry"]

if "apple" in fruits:
    print("苹果在水果列表中。")

if "orange" in fruits:
    print("橙子在水果列表中。")
else:
    print("橙子不在水果列表中。")

# 检查字符串
text = "Hello, World!"
if "World" in text:
    print("'World' 在字符串中。")

# 检查元组
numbers = (1, 2, 3, 4, 5)
if 3 in numbers:
    print("3 在元组中。")

输出:

苹果在水果列表中。
橙子不在水果列表中。
'World' 在字符串中。
3 在元组中。

not in 运算符

not in 运算符用于检查一个元素是否不在一个序列中,如果不在则返回真,否则返回假。

示例:

python
# not in 运算符示例
fruits = ["apple", "banana", "cherry"]

if "orange" not in fruits:
    print("橙子不在水果列表中。")

if "apple" not in fruits:
    print("苹果不在水果列表中。")
else:
    print("苹果在水果列表中。")

# 检查字符串
text = "Hello, World!"
if "Python" not in text:
    print("'Python' 不在字符串中。")

输出:

橙子不在水果列表中。
苹果在水果列表中。
'Python' 不在字符串中。

身份运算符

身份运算符用于检查两个对象是否是同一个对象(即是否指向同一个内存地址)。Python 提供了 isis not 运算符。

is 运算符

is 运算符用于检查两个对象是否是同一个对象,如果是则返回真,否则返回假。

示例:

python
# is 运算符示例
x = 10
y = 10
z = x

print(f"x is y: {x is y}")  # 输出:x is y: True
print(f"x is z: {x is z}")  # 输出:x is z: True

# 对于小整数,Python 会缓存
x = 256
y = 256
print(f"x is y: {x is y}")  # 输出:x is y: True

# 对于大整数,Python 不会缓存
x = 257
y = 257
print(f"x is y: {x is y}")  # 输出:x is y: False

# 对于字符串
x = "hello"
y = "hello"
print(f"x is y: {x is y}")  # 输出:x is y: True

# 对于列表
x = [1, 2, 3]
y = [1, 2, 3]
print(f"x is y: {x is y}")  # 输出:x is y: False(列表是可变的,即使值相同也是不同的对象)

is not 运算符

is not 运算符用于检查两个对象是否不是同一个对象,如果不是则返回真,否则返回假。

示例:

python
# is not 运算符示例
x = 10
y = 20

print(f"x is not y: {x is not y}")  # 输出:x is not y: True

x = [1, 2, 3]
y = [1, 2, 3]
print(f"x is not y: {x is not y}")  # 输出:x is not y: True

x = "hello"
y = x
print(f"x is not y: {x is not y}")  # 输出:x is not y: False

比较运算符

比较运算符用于比较两个值的大小或相等性,返回布尔值 TrueFalse

运算符描述示例
==等于x == y
!=不等于x != y
>大于x > y
<小于x < y
>=大于等于x >= y
<=小于等于x <= y

示例:

python
# 比较运算符示例
x = 10
y = 5

print(f"x == y: {x == y}")  # 输出:x == y: False
print(f"x != y: {x != y}")  # 输出:x != y: True
print(f"x > y: {x > y}")  # 输出:x > y: True
print(f"x < y: {x < y}")  # 输出:x < y: False
print(f"x >= y: {x >= y}")  # 输出:x >= y: True
print(f"x <= y: {x <= y}")  # 输出:x <= y: False

# 比较字符串
str1 = "apple"
str2 = "banana"
print(f"str1 == str2: {str1 == str2}")  # 输出:str1 == str2: False
print(f"str1 < str2: {str1 < str2}")  # 输出:str1 < str2: True(按字典序比较)

条件控制的应用场景

条件控制在编程中非常常见,以下是一些典型的应用场景:

  1. 用户输入验证:检查用户输入是否符合要求。
  2. 游戏逻辑:根据游戏状态执行不同的操作。
  3. 数据处理:根据数据的特点执行不同的处理逻辑。
  4. 错误处理:处理可能出现的错误情况。
  5. 菜单选择:根据用户的选择执行不同的功能。

示例:

python
# 条件控制的应用场景

# 1. 用户输入验证
print("1. 用户输入验证")
user_input = input("请输入一个数字:")

if user_input.isdigit():
    number = int(user_input)
    print(f"你输入的数字是:{number}")
else:
    print("你输入的不是一个有效的数字。")

# 2. 游戏逻辑
print("\n2. 游戏逻辑")
score = 85

if score >= 90:
    print("恭喜你,获得了金牌!")
elif score >= 80:
    print("不错,获得了银牌。")
elif score >= 70:
    print("加油,获得了铜牌。")
else:
    print("继续努力,下次一定会更好!")

# 3. 数据处理
print("\n3. 数据处理")
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
odd_numbers = []

for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)
    else:
        odd_numbers.append(num)

print(f"偶数:{even_numbers}")
print(f"奇数:{odd_numbers}")

# 4. 错误处理
print("\n4. 错误处理")
try:
    x = int(input("请输入一个数字:"))
    y = int(input("请输入另一个数字:"))
    result = x / y
    print(f"结果是:{result}")
except ZeroDivisionError:
    print("错误:除数不能为零。")
except ValueError:
    print("错误:请输入有效的数字。")

# 5. 菜单选择
print("\n5. 菜单选择")
print("请选择一个选项:")
print("1. 查看个人信息")
print("2. 修改密码")
print("3. 退出")

choice = input("请输入选项编号:")

if choice == "1":
    print("查看个人信息...")
elif choice == "2":
    print("修改密码...")
elif choice == "3":
    print("退出程序...")
else:
    print("无效的选项。")

总结

Python 中的条件控制语句包括 ifelifelse,用于根据不同的条件执行不同的代码块。此外,Python 还提供了条件表达式、逻辑运算符、成员运算符和身份运算符等工具,用于构建更复杂的条件逻辑。掌握条件控制语句对于编写 Python 代码非常重要。