《Python编程:从入门到实践》读书笔记——第5章:if语句

条件测试

每条if语句的核心都是一个值为True或False的表达式,这种表达式称为条件测试。如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;如果False, Python就忽略这些代码。

检查是否相等

使用两个等号(==)检查一个变量的当前值是否等于某个特定值。

>>>car='bmw'
>>>car=='bmw'

True

注意在检查是否相等时区分大小写。

>>>car='Audi'
>>>car=='audi'

False

如果大小写无关紧要,只是想检查变量的值,可以使用方法lower()将变量的值转换为小写,再进行比较, 而且方法lower()并不会改变存储在变量中的值:

car='Audi'
car.lower()=='audi'
car

True
'Audi'

当网站想要确保用户名是独一无二的,而不是与其他用户名大小写不同时,可以使用类似的测试方法。

检查是否不相等

结合使用惊叹号和等号(!=),来判断两个值是否相等。

**toppings.py**
requested_topping='mushrooms'
if requested_topping != 'anchovies':
   print('Hold the anchovies!')

Hold the anchovies!

数字比较

条件语句中可以使用任何比较:

>>>age=17
>>>age<21
True
>>>age<=21
True
>>>age>21
False
>>>age>=21
False
>>>age==17
True
>>>age!=20
True

检查多个条件

1.使用and检查多个条件
要检查两个条件是否都为True,可使用关键字and将两个条件测试合二为一:如果每个测试都通过了,整个表达式就为True; 如果至少有一个测试没有通过,整个表达式就为False:

>>>age_0=22
>>>age_1=18
>>>age_0>=21 and age_1>=21
False
>>>age_1=22
>>>age_0>=21 and age_1>=21
True

为了提高可读性,还可以将每个测试分别放在一对括号里。

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

2.使用or检查多个条件

>>>age_0=22
>>>age_1=18
>>>age_0>=21 or age_1>=21
True
>>>age_0=19
>>>age_0>=21 and age_1>=21
False

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

使用in判断特定值是否包含在列表中。

>>>requested_toppings=['mushrooms','onions','pineapple']
>>>'mushrooms' in requested_toppings
True
>>>'pepperoni' in requested_toppings
False

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

使用关键字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.

布尔表达式

它是条件测试的别名,其结果要么为True,要么为False.

game_active=True
can_edit=False

if语句

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

简单的if语句

简单的if语句只有一个测试和一个操作:

**voting.py**
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?

在if语句中,缩进的作用与for循环中相同。如果测试通过,将执行if语句后面所有缩进的代码行,否则将忽略它们。

if-else语句

if-else语句块类似于简单的if语句,但其中的else语句使在指定条件未通过时执行另一个操作。因此,if-else结构适合要让Python执行两种操作之一的情形。

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!

if-elif-else结构

需要检查超过两个的条件测试时,可以使用if-elif-else结构。

#三个测试条件
age=12
if age < 4:
    price = 0
elif age < 18:
    price = 5
else:
    price = 10
print('Your admission cost is $'+str(price)+'.')

Your admission cost is $5.
#可根据需要使用任意数量的elif代码块
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)+'.')

Your admission cost is $5.

省略else代码块

else是一个包罗万象的语句,只要不满足if或elif中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个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)+'.')

Your admission cost is $5.

测试多个条件

有时候需要检查多个条件,并且在每个条件为True时都会采取相应措施。此时,可以使用多个简单的if语句。

**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('\nFinished making your pizza!')

Adding mushrooms.
Adding extra cheese.

Finished making your pizza!

当只需要执行一个代码块时,用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('Adding '+requested_topping+'.')
print('\nFinished making your pizza!')

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

Finished making your pizza!    

确定列表不是空的

运行for循环前确定列表不为空非常重要。

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?')

Are you sure you want a plain pizza?

在if语句中将列表名用在条件表达式中,Python将在列表中至少包含一个元素时返回True,并在列表为空时返回False.

使用多个列表

当判断是否能够满足顾客的要求时,会用到两个列表。

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 do not have '+requested_topping+'.')
print('\nFinished making your pizza!')

Adding mushrooms.
Sorry, we do not have french fries.
Adding extra cheese.
Finished making your pizza!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值