第五章 if 语句

5.1 一个简单示例

遍历一个列表,如果是‘bmw’,就全部大写,其余的只首字母大写

cars = ['audi', 'bmw', 'subaru', 'toyota']

for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())
'''
输出:
Audi
BMW
Subaru
Toyota

'''

5.2 条件测试

if 后面跟一个表达式,用这个表达式进行条件测试,如果测试值为 True,则执行紧跟在 if 语句后面的代码,如果为 False,则忽略这些代码

5.2.1 检查是否相等

注意 ’=‘ 和 ’==‘的区别
’ = ‘为赋值
’ == ‘为逻辑判断等于

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

python对大小写敏感,大小写不同会被认为是不同的值
在大小写无关紧要的情况下,可以采用如下方法比较:

car = 'Audi'
car.lower() == 'audi' #返回为True,但car的值还是'Audi'

5.2.3 检查是否不相等

判断不相等,可以用( != )

5.2.4 数值比较

等于 ( == )
不等于 ( != )
大于 ( > )
小于 ( < )
大于等于 ( >= )
小于等于 ( <= )

5.2.5 检查多个条件

  1. 使用 and 检查多个条件
    只有每个条件都为真,整个表达式才为真
    推荐代码这样写,可以提高代码的可读性
(age_0 >= 21) and (age_1 >= 21)
  1. 使用 or 检查多个条件
    至少有一个条件为真,整个表达式才为真

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

使用关键字 in

cars = ['audi', 'bmw', 'subaru', 'toyota']

print('bmw' in cars)
print('honda' in cars)
'''
输出:
True
False

'''

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

使用关键字 not in

5.2.8 布尔表达式

例如: game_active = True

5.3 if 语句

5.3.1 简单的 if 语句

if conditional_test:
    do something

如果测试代码为真,则执行紧跟在后面的有缩进的代码块,如果为假,则不会执行紧跟在后面的有缩进的代码块

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?

'''

5.3.2 if - else 语句

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 are 18!")
'''
输出:
Sorry,you are too young to vote!
Please register to vote as soon as you are 18!

'''

5.3.3 if - elif - else 结构

如果检查查过两种情形,就是用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}.")
'''
输出:
Your admission cost is $25.

'''

5.3.4 使用多个 elif 代码块

可以根据需要将 5.3.4中的 elif 由1个改为任意个

5.3.5 省略 else 代码块

else 代码块并不是必须的

5.3.5 测试多个条件

if - elif -……… - else 结构仅适用于满足一种条件,换言之,只要满足其中的一个测试,程序就会跳过其余的测试
对于关心所有条件的情形,我们用不包括 elif 和 else 的多个独立的 if 语句来解决

  1. 多个 if 语句的情形
request_toppings = ['mushrooms', 'extra cheese']

if 'mushrooms' in request_toppings:
    print('Adding mushrooms.')
if 'pepperoni' in request_toppings:
    print('Adding pepperoni.')
if 'extra cheese' in request_toppings:
    print('Adding extra cheese.')

print('\nFinished making your pizza.')

'''
输出:
Adding mushrooms.
Adding extra cheese.

Finished making your pizza.

'''
  1. if - elif- elif语句的情形
request_toppings = ['mushrooms', 'extra cheese']

if 'mushrooms' in request_toppings:
    print('Adding mushrooms.')
elif 'pepperoni' in request_toppings:
    print('Adding pepperoni.')
elif 'extra cheese' in request_toppings:
    print('Adding extra cheese.')

print('\nFinished making your pizza.')
'''
输出:
Adding mushrooms.

Finished making your pizza.

'''

通过对比发现,我们需要的配料有 ‘mushrooms’ 和 ‘extra cheese’,例1的代码实现了我们的需求,但例2的代码却没有实现,这是因为在 if - elif - elif 结构中,只要有一个符合条件,就不再检查其余条件,因此在该例中当’mushrooms’ 通过测试后,直接就跳过了余下的代码测试。

5.4 使用 if 语句处理列表

5.4.1 检查特殊元素

青椒用完了,所以就没办法添加进去了,所以每次添加材料时要进行检查,如果市青椒,就输出:用完了,其它情况;输出:添加 xxx

request_toppings = ['mushrooms', 'green peppers', 'extra cheese']

for request_topping in request_toppings:
    if request_topping == 'green peppers':
        print('Sorry, we are out of green peppers.')
    else:
        print(f'Adding {request_topping}.')

print('\nFinished making your pizza.')
'''
输出:
Adding mushrooms.
Sorry, we are out of green peppers.
Adding extra cheese.

Finished making your pizza.

'''

5.4.2 确定列表不是空的

检查列表是否为空,如果不空,则依次添加需要的配料,如果为空,则发出询问:您想要一块原味披萨吗?

  1. 列表为空
request_toppings = []

if request_toppings:
    for request_topping in request_toppings:
        print(f"Add {request_topping}.")
    print("\nFinished making your pizza.")
else:
    print("Are you sure you want a plain pizza?")

'''
输出:
Are you sure you want a plain pizza?

'''
  1. 列表不为空
request_toppings = ['mushrooms', 'green peppers', 'extra cheese']

if request_toppings:
    for request_topping in request_toppings:
        print(f"Add {request_topping}.")
    print("\nFinished making your pizza.")
else:
    print("Are you sure you want a plain pizza?")
'''
输出:
Add mushrooms.
Add green peppers.
Add extra cheese.

Finished making your pizza.

'''

5.4.3 使用多个列表

定义两个列表,第一个列表存披萨店有的配料,第二个列表存顾客想要的配料,对于顾客想要的配料,如果披萨店有就添加,如果没有就说没有,遍历完顾客想要的列表后结束

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

for request_topping in request_toppings:
    if request_topping in available_toppings:
        print(f"Adding {request_topping}.")
    else:
        print(f"Sorry, we don't have {request_topping}.")
print("\nFinished making your pizza.")
'''
输出:
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.

Finished making your pizza.
'''

5.5 设置 if 语句的格式

建议比较运算符两边各添加一个空格
如:“ if age < 4:”要比 “if age<4:”更好

5.6 小结

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张小勇zhangxy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值