Python中的条件语句如何编写?
2025年9月16日 by admin
在 Python 中,条件语句用于根据不同的条件执行不同的代码。常见的条件语句有 if、elif 和 else。
if 语句if 语句用于判断一个条件是否为 True,如果为 True,则执行相应的代码块。
if condition:
# 条件为 True 时执行的代码
age = 18
if age >= 18:
print("You are an adult.")
输出:
You are an adult.
elif 语句elif 语句是 else if 的缩写,用于检查多个条件。如果 if 条件不成立,程序会检查 elif 中的条件。
if condition1:
# 条件1为 True 时执行的代码
elif condition2:
# 条件2为 True 时执行的代码
age = 16
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
输出:
You are a teenager.
else 语句else 语句用于在所有条件不成立时执行。如果 if 和 elif 中的条件都不满足,则会执行 else 部分的代码。
if condition1:
# 条件1为 True 时执行的代码
elif condition2:
# 条件2为 True 时执行的代码
else:
# 所有条件都不满足时执行的代码
age = 10
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
输出:
You are a child.
可以使用 and 和 or 来组合多个条件,进行更复杂的判断。
and:多个条件都为 True 时才会执行。or:只要有一个条件为 True,就会执行。and):age = 20
has_permission = True
if age >= 18 and has_permission:
print("You can enter.")
输出:
You can enter.
or):age = 16
has_permission = False
if age >= 18 or has_permission:
print("You can enter.")
else:
print("You cannot enter.")
输出:
You cannot enter.
if:检查一个条件,条件为 True 时执行。elif:检查多个条件。else:所有条件都不满足时执行。and:多个条件都为 True 时执行。or:多个条件中只要有一个为 True 就执行。