Python编程从入门到实践(四)-if语句

本文详细介绍了Python中的if语句,包括条件测试、比较运算符、if-else和if-elif-else结构的使用,以及如何在处理列表时运用if语句。示例涵盖了从简单的条件判断到复杂的列表检查,帮助读者掌握Python条件控制的精髓。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 一个简单示例
假设你有一个汽车列表,并想将其中每辆汽车的名称打印出来。对于大多数汽车,都应以首字母大写的方式打印其名称,但对于汽车名’bmw',应以全大写的方式打印。下面的代码遍历一个列表,并以首字母大写的方式打印其中的汽车名,但对于汽车名’bmw',以全大写的方式打印:

cars = ['audi','bmw','subaru','toyota']
for car in cars:
    if car=='bmw':
        print(car.upper())
    else:
        print(car.title())

输出:
Audi
BMW
Subaru
Toyota
2 条件测试

2.1 python中两个字母相比较时区分大小写,但可以用 lower()或upper()
2.2比较数字
条件语句中可包含各种数学比较,如等于、不等于、小于、小于等于、大于、大于等于:
>>> age = 19>>> age < 21True
>>> age <= 21True
>>> age > 21False
>>> age >= 21False
2.3 检查多个条件
 (1)使用关键字andor
 (2)检查特定值是否包含在列表中,可使用关键字in

requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)

(3) 检查特定值是否不包含在列表中,可使用关键字not in

#banned_users.py
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
       print(user.title() + ", you can post a response if you wish.")

输出:
Marie, you can post a response if you wish.
3 if语句
3.1假设有一个表示某人年龄的变量,而你想知道这个人是否够投票的年龄,可使用如下代码

#voting.py
age = 19
if age >= 18:
    print("You are old enough to vote! ")

输出:
You are old enough to vote!
在if语句中,缩进的作用与for循环中相同。如果测试通过了,将执行if语句后面所有缩进的代码行,否则将忽略它们。
在紧跟在if语句后面的代码块中,可根据需要包含任意数量的代码行。下面在一个人够投票的年龄时再打印一行输出,问他是否登记了:

age = 19
if age >= 18:
    print("You are old enough to vote! ")
    print("Have you registered to vote yet? ")

输出:
You are old enough to vote!
Have you registered to vote yet?
3.2 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 soon as you turn 18! ")

输出:
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
3.3 if-elif-else结构
例如,来看一个根据年龄段收费的游乐场:
❑ 4岁以下免费;
❑ 4~18岁收费5美元;
❑ 18岁(含)以上收费10美元。
下面的代码确定一个人所属的年龄段,并打印一条包含门票价格的消息:

#amusement_park.py
age = 12
if age < 4:
    print("Your admission cost is $0.")
elif age < 18:
    print("Your admission cost is $5.")
else:
    print("Your admission cost is $10.")

输出:
Your admission cost is $5.
为让代码更简洁,可不在if-elif-else代码块中打印门票价格,而只在其中设置门票价格,并在它后面添加一条简单的print语句:

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
else:
    price = 10
print("Your admission cost is $" + str(price) + ".")

3.4 使用多个elif代码块
例如,假设前述游乐场要给老年人打折,可再添加一个条件测试,判断顾客是否符合打折条件。下面假设对于65岁(含)以上的老人,可以半价(即5美元)购买门票:

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 5
print("Your admission cost is $" + str(price) + ".")

3.5 省略else代码块
Python并不要求if-elif结构后面必须有else代码块。在有些情况下,else代码块很有用;而在其他一些情况下,使用一条elif语句来处理特定的情形更清晰:

age = 12
if age<4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
elif age >= 65:
    price = 5
print("Your admission cost is $" + str(price) + ".")

elif代码块在顾客的年龄超过65(含)时,将价格设置为5美元,这比使用else代码块更清晰些。经过这样的修改后,每个代码块都仅在通过了相应的测试时才会执行。
else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块。这样,你就可以肯定,仅当满足相应的条件时,你的代码才会执行。
3.6 测试多个条件
下面再来看前面的比萨店示例。如果顾客点了两种配料,就需要确保在其比萨中包含这些配料:

#toppings.py
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("\n Finished making your pizza! ")

输出:
Adding mushrooms.
Addingextracheese.

    Finished making your pizza!
4 使用if语句处理列表
4.1 检查特殊元素
下面来进一步研究如何检查列表中的特殊值,并对其做合适的处理。
继续使用前面的比萨店示例。这家比萨店在制作比萨时,每添加一种配料都打印一条消息。通过创建一个列表,在其中包含顾客点的配料,并使用一个循环来指出添加到比萨中的配料,可以以极高的效率编写这样的代码:

#toppings.py
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
    print("Adding " + requested_topping + ".")
print("\n Finished making your pizza! ")

输出:
Adding mushrooms.
Adding green peppers.
Adding extra cheese.

  Finished making your pizza!
然而 如果比萨店的青椒用完了,该如何处理呢?为妥善地处理这种情况,可在for循环中包含一条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("Adding " + requested_topping + ".")
print("\n Finished making your pizza! ")

输出:
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.

  Finished making your pizza!
4.2 确定列表不是空的
下面在制作比萨前检查顾客点的配料列表是否为空。如果列表是空的,就向顾客确认他是否要点普通比萨;如果列表不为空,就像前面的示例那样制作比萨:

requested_toppings = []
if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding " + requested_topping + ".")
    print("\nFinished making your pizza! ")
else:
    print("Are you sure you want a plain pizza? ")

输出:
Areyousureyouwantaplainpizza?
如果这个列表不为空,将显示在比萨中添加的各种配料的输出。
4.3 使用多个列表
下面的示例定义了两个列表,其中第一个列表包含比萨店供应的配料,而第二个列表包含顾客点的配料。这次对于requested_toppings中的每个元素,都检查它是否是比萨店供应的配料,再决定是否在比萨中添加它:

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("Adding " + requested_topping + ".")
    else:
        print("Sorry, we don't have " + requested_topping + ".")
print("\n Finished making your pizza! ")

输出:
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.

  Finished making your pizza!
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值