Python : IF 语句
了解条件测试后,您可以开始使用 if语句来控制 Python 程序的流程。
if语句有多种类型 ,您选择的语句取决于要检查的条件数量。
简单的if语句:
一个简单的 if 语句测试一个条件并根据结果执行操作:
if conditional_test:
# Do something
该条件的计算结果为 True 或 False。
如果为 True,则执行缩进块内的代码。否则,Python 会跳过该块。
例如,您可以检查一个人是否达到可以投票的年龄:
age = 19
if age >= 18:
print("You are old enough to vote!")
这将打印消息,因为条件 (age >= 18) 为 True。
if-else语句:
在许多情况下,您需要根据条件是通过还是失败来采取不同的操作。
这就是 if-else 结构的用武之地:
age = 17
if age >= 18:
print("You are old enough to vote!")
else:
print("Sorry, you are too young to vote.")
在这里,如果条件 (age >= 18) 为 False,Python 将执行 else 块,打印不同的消息。
if-elif-else链:
当您需要测试多个条件时,请使用 if-elif-else 链。Python 按顺序评估每个条件,并执行第一个通过的测试的块:
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $25.")
else:
print("Your admission cost is $40.")
>>
Your admission cost is $25.
在这里,第二次测试(年龄 x3C 18)通过了,所以打印了“您的入场费是 25 美元”的信息。
多个elif块:
您可以添加更多 elif块来处理更复杂的情况。
例如,如果您想添加高级折扣:
age = 70
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
else:
price = 20
print(f"Your admission cost is ${price}.")
在这种情况下,如果此人年满 65 岁,则价格将为 20 美元,如 else块中指定。
省略else块:
你并不总是需要一个 else块。
如果有特定的条件要测试,可以将 else块替换为另一个 elif语句:
age = 70
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
elif age >= 65:
price = 20
print(f"Your admission cost is ${price}.")
这种方法可确保仅在满足正确条件时执行每个代码块,从而对程序的行为提供更多控制。
测试多个条件:
有时,您希望单独检查多个条件。
在这些情况下,请使用多个 if 语句,而不使用 elif 或 else:
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
在此示例中,Python 分别检查每个条件,因此它会将蘑菇和额外的奶酪添加到披萨中。
如果你使用了 if-elif-else 结构,
Python 将在第一个条件通过后停止检查:
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
This code would only add mushrooms and skip the rest,因为 Python 在第一个条件为 True 后停止检查。
当您需要测试一个条件时,请使用简单的 if 语句。
如果希望在条件通过时运行一个代码块,如果条件通过,则运行另一个代码块,请使用 if-else。
当您需要检查多个条件时,请使用 if-elif-else。
当需要检查多个条件并且可能需要多个操作时,请使用多个 if 语句。