Python if 语句|Python 主题月

844 阅读4分钟

本文正在参加「Python主题月」,详情查看 活动链接

编程时经常需要检查一系列条件,并据此决定采取什么措施。在 Python 中,if语句让你能够检查程序的当前状态,并采取相应的措施。

简单示例

  • 下面是一个简短的示例,演示了如何使用 if 语句来正确地处理特殊情形。假设你有一个汽车列表,并想将其中每辆汽车的名称打印出来。对于 BMW,汽车名需要全大写。
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

测试条件

  • 每条 if 语句的核心都是一个值为 True 或 False 的表达式,这种表达式称为条件测试
  • Python 根据条件测试的值为 True 还是 False 来决定是否执行 if 语句中的代码。

检查是否相等

  • 最简单的条件测试检查变量的值是否与特定值相等:
In [1]: car = 'bmw'

In [2]: car == 'bmw'
Out[2]: True
  • 这个相等运算符在两边的值相等时返回 True,否则返回 False。

检查是否相等时忽略大小写

  • 在 Python 中检查是否相等时区分大小写。
In [1]: car = 'Audi'

In [2]: car == 'audi'
Out[2]: False
  • 如果大小写很重要,这种行为有其优点。但如果大小写无关紧要,只想检查变量的值,可将变量的值转换为小写,再进行比较:
In [1]: car = 'Audi'

In [2]: car == 'audi'
Out[2]: False

In [3]: car.lower() == 'audi'
Out[3]: True

In [4]: car
Out[4]: 'Audi'
  • 方法 lower() 并没有影响关联到变量 car 的值。

检查是否不相等

  • 下面再使用一条if语句来演示如何使用不等运算符:
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
    print("Hold the anchovies!")

数值比较

answer = 17
if answer != 42:
    print("That is not the correct answer. Please try again!")

检查多个条件

  1. 使用 and 检查多个条件
  • 例如,检查两个人是否都小于 21 岁:
age_0 = 22
age_1 = 18

print(age_0 >= 21 and age_1 >= 21)

age_1 = 22

print(age_0 >= 21 and age_1 >= 21)
  1. 使用 or 检查多个条件
  • 下面再次检查两个人的年龄,但检查的条件是至少一个人的年龄不小于 21 岁:
age_0 = 22
age_1 = 18

print(age_0 >= 21 or age_1 >= 21)

age_1 = 18

print(age_0 >= 21 or age_1 >= 21)

检查特定值是否包含在列表中

  • 有时候,执行操作前必须检查列表是否包含特定的值。
  • 要判断特定的值是否已包含在列表中,可使用关键字 in
requested_toppings = ['mushrooms', 'onions', 'pineapple']

print('mushrooms' in requested_toppings)

print('pepperoni'in requested_toppings)

检查特定值是否不包含在列表中

  • 还有些时候,确定特定的值未包含在列表中很重要。在这种情况下,可使用关键字 not in
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
    print(f"{user.title()}, you can post a response if you wish.")

布尔表达式

  • 它不过是条件测试的别名。
  • 与条件表达式一样,布尔表达式的结果要么为 True,要么为 False

if 语句

  • if 语句有很多种,选择使用哪种取决于要测试的条件数。

简单的 if 语句

  • 最简单的 if 语句只有一个测试和一个操作:
age = 19

if age >= 18:
    print("You are old enough to vote!")

if-else 语句

  • 我们经常需要在条件测试通过时执行一个操作,在没有通过时执行另一个操作。
age = 17

if age >= 18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:
    print("Sorry, you are too young to vote.")
    print("Please register to vote as soo as you are 18!")

if-elif-else 结构

  • 我们经常需要检查超过两个的情形,为此可使用 Python 提供的 if-elif-else 结构。
age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 25
else:
    price = 40
print(f"Your admission cost is ${price}")

使用多个 elif 代码块

  • 可根据需要使用任意数量的 elif 代码块。
age = 12

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}")

省略 else 代码块

  • Python 并不要求 if-elif 结构后面必须有 else 代码块。
age = 12

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 结构;如果要执行多个代码块,就使用一系列独立的 if 语句。

使用if语句处理列表

  • 结合使用 if 语句和列表

检查特殊元素

  • 制作披萨,但是没有青椒了:
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']

for requested_topping in requested_toppings:
    if requested_topping == 'green peppers':
        print("Sorry, we are out of green peppers right now.")
    else:
        print(f"Adding {requested_topping}")

print("\nFinished making your pizza!")

确定列表不是空的

  • 在制作比萨前检查顾客点的配料列表是否为空。如果列表为空,就向顾客确认是否要点原味比萨;如果列表不为空,就像前面的示例那样制作比萨:
requested_toppings = []

if requested_toppings:
    for requested_topping in requested_toppings:
        print(f"Adding {requested_topping}")
    
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")

使用多个列表

available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']

requested_toppings = ['mushrooms', 'french fries', 'extra cheese']

for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print(f"Adding {requested_topping}.")
    else:
        print(f"Sorry, we don't have {requested_topping}")

print("\nFinished making your pizza!")

设置 if 语句的格式

  • 在条件测试的格式设置方面,PEP 8 提供的唯一建议是,在诸如 ==、>= 和 <= 等比较运算符两边各添加一个空格