阅读《Python编程从入门到实践》Day04

第五章

1、一个简单示例

cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())
# 输出:
Audi
BMW
Subaru
Toyota

上述例子遍历一个汽车名的列表,并以首字母大写的方式打印出来,但是当遇到“bmw”的时候,就要全部字母大写打印。

2、条件测试

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

(1)检查是否相等

大多数条件测试都是将一个变量的当前值同特定值进行比较。比较两个值是否相等,用两个等号(==)来比较。若两边的值相等,返回True,否则返回False。

(2)检查是否相等大小写的问题

在Python中检查大小写是区分大小写的,即同样的单词,大写与小写相比较的结果是不等的。
如果要进行大小写不重要的相等比较时,可以用字符串中的方法对其进行相应的处理再进行比较。网站采用类似的方式让用户输入的数据符合特定的格式,比如确保每个用户名都是独一无二的,当你用相应的大写或者小写进行用户名注册时,就会遭到拒绝。

(3)检查是否不相等

判断两个值是否不等,用感叹号和等号(!=)来比较。两边的值不相等时,返回True,否则返回False。合理有效的使用(==)和(!=),可以提高一定的效率。

(4)比较数字

比较数字中,除了比较等于和不等于,还有小于(<)、小于等于(<=)、大于(>)、大于等于(>=)等等,当条件成立时,返回True,否则返回False。

(5)检查多个条件

使用and检查多个条件:
当要检查是否两个条件都为True时,可以使用关键字and将两个条件测试合二为一;如果两个条件都为True,则整个表达式就为True;如果至少有一个条件为False,整个表达式就为False。如检查是否两个人都不小于21岁:

age_0 = 22
age_1 = 18
print((age_0 >= 21) and (age_1 >= 21))
# 输出:
False
age_0 = 22
age_1 = 25
print((age_0 >= 21) and (age_1 >= 21))
# 输出:
True

使用or检查多个条件:
关键字or只要至少有一个条件为True,整个表达式就为True。只有当两个条件都为False时,整个表达式才为False。

age_0 = 22
age_1 = 18
print((age_0 >= 21) or (age_1 >= 21))
# 输出:
True
age_0 = 20
age_1 = 18
print((age_0 >= 21) or (age_1 >= 21))
# 输出:
False
(6)检查特定值是否包含在列表中

可使用关键字in来判断特定的值是否包含在列表中。

requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)
# 输出:
True
False
(7)检查特定值是否不包含在列表中

使用关键字not in来判断特定的值是否不包含在列表中。

requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' not in requested_toppings)
print('pepperoni' not in requested_toppings)
# 输出:
False
True
(8)布尔表达式

布尔表达式,就是条件测试的别名。与条件表达式一样,它的结果不是True就是False。布尔值通常用于记录条件。

game_active = True

3、if 语句

(1)简单的 if 语句

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

age = 20
if age >= 18:
    print('You are old enough to vote!')
# 输出:
You are old enough to vote!

在 if 语句中,缩进的作用与for循环中的作用一样。如果测试通过了,将执行 if 语句后面所有缩进的代码行,否则将忽略它们。在紧跟在 if 语句后面的代码块中,可根据需要包含任意数量的代码行。

(2)if-else语句

当在条件测试中,若要在通过时执行一个操作,没通过时执行另外一个操作,可使用 if-else 语句。

age = 16
if age >= 18:
    print('You are old enough to vote!')
else:
    print('Sorry, you are too young to vote.')
# 输出:
Sorry, you are too young to vote.

if-else语句适合用于只有两种情形的判断,如上述代码中,条件成立,执行 if 后的语句,若不成立,则执行else后的语句。

(3)if-elif-else 结构

当条件测试的结果超过两种情形,可使用 if-elif-else 结构。Python只执行结构中的一个代码块,它依次检查每个条件测试,直到遇到了通过了的条件测试。测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的代码。其中的elif代码块可根据需要添加任意数量。如游乐园的门票问题:

age = 15
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 8
print('Your admission cost is $' + str(price) + '.')
# 输出:
Your admission cost is $5.
(4)省略else代码块

Python并不要求 if 语句后面必须要有else代码块。else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块。这样,你就可以肯定,仅当满足相应的条件时,你的代码才会执行。

(5)测试多个条件

当你需要检查每一个条件时,就应使用一系列不包含elif和else代码块的简单 if 语句。在可能有多个条件为True,且你需要在每个条件为True时都采取相应的措施时,适合使用这种方法。如披萨店中顾客点配料的例子中:

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('Finished making your pizza!')
# 输出:
Adding mushrooms.
Adding extra cheese.
Finished making your pizza!

如果你想只执行一个代码块,就使用if-elif-else结构;如果要运行多个代码块,就使用一系列独立的 if 语句。

4、使用 if 语句处理列表

(1)检查特殊元素

继续上述披萨店的例子,当顾客点的配料用完时的处理:

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('Finished making your pizza!')
# 输出:
Addingmushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!
(2)确定列表不是空的

继续上述例子,当顾客没有点任何配料时,列表是空的,此时,需要向顾客确认一下。

requested_toppings = []
if requested_toppings:
    for requested_topping in requested_toppings:
        print('Adding' + requested_topping + '.')
    print('Finished making your pizza!')
else:
    print('Are you sure you want a plain pizza?')
# 输出:
Are you sure you want a plain pizza?
(3)使用多个列表
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('Finished making your pizza!')
# 输出:
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.
Finished making your pizza!
(5)设置 if 语句的格式

在条件测试的格式设置方面,PEP 8提供的唯一建议是,在诸如==、>=和<=等比较运算符两边各添加一个空格。这样的空格不会影响Python对代码的解读,而只是让阅读代码的人理解起来更容易,同时也更美观。

    原文作者:晓梅_aa3b
    原文地址: https://www.jianshu.com/p/ad877342fcb6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞