第5章 IF 语句

知识点:

# 编程时经常需要检查一系列条件,并据此决定采取什么措施。在Python中,if语句让你能够检查程序当前的状态,并据此采取相应的措施。
# 5.1一个简单示例
# 假设你有一个汽车列表,并想将其中每辆汽车的名称打印出来。对于大多数汽车,都应以首字母大写的 方式打印其名称,
# 但对于汽车名'bmw' ,应以全大写的方式打印。下面的代码遍历一个列表,并以首字母大写的方式打印其中的汽车名,但对于汽车名'bmw' ,以全大写的方 式打印:

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

# 5.2 条件测试
# 每条if语句的核心都是一个值为True或False 的表达式,这种表达式被称为条件测试。
# Python 根据条件测试的值为True还是False来决定是否执行if语句中的代码。如果条件测试的值为True,Python就执行紧跟在if语句后面的代码:如果时False,Python 就忽略这些代码。
# 5.2.1 检查是否相等。
# 大多数条件测试都是将一个变量的当前值同特定值进行比较。最简单的条件测试检查变量的值是否与特定值相等。
'''
car = 'bmw'
car == 'bmw'
'''
# 首先使用一个等号将car的值设置为'bmw',接下来,使用两个等号(==)检查是否为'bmw'.这个相等运算符在它两边的值相等时返回True,否则返回False.
'''
car = 'audi'
car == 'bmw'
'''
# 5.2.2 检查是否相等时不考虑大小写
# 在Python 中检查是否相等时区分大小写,例如,两个大小写不同的值会被视为不相等。
'''
car = 'Audi'
car.lower() == 'audi'

car.upper() == 'audi'
'''
# 网站采用类似的方式让用户输入的数据符合特定的格式。
# 例如,网站可能使用类似来确保用户是独一无二的,而并非只是与另一个用户名大小写不同。
# 用户提交新的用户名时,将把它转换为大小写,并与所有既有用户名的小写版本进行比较。
# 执行这种检查时,,如果已经有用户名'john' (不管大小写如何),则用户提交用户名'John' 时将 遭到拒绝。

# 5.2.3 检查是否不相等

# 要判断两个值是否不等,可结合使用惊叹号和等号(!=),其中的惊叹号表示不,在很多编程语言中都是如此。
'''
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
    print("Hold the anchovies!")
'''
# 你编写的大多数条件表达式都检查两个值是否相等,但有时候检查两个值是否不等的效率更高。

# 5.2.4 比较数字
# 检查数值非常简单,例如,下面的代码检查一个人是否是18岁:
'''
age = 18
age == 18
'''
# 你还可以检查两个数字是否不等,例如,下面的代码在提供的答案不正确时打印一条消息:
'''
answer = 17
if answer != 42:
    print("That is not the correct answer.Please try again!")
'''

# 5.2.5 检查多个条件  
# 检查多个条件 你可能想同时检查多个条件,
# 例如,有时候你需要在两个条件都为True 时才执行相应的操作,
# 而有时候你只要求一个条件为True 时就执行相应的操作。
# 在这些情况下,关键 字and 和or 可助你一臂之力

# 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
'''

# 2. 使用 使用or 检查多个条件 检查多个条件 关键字or 也能够让你检查多个条件,但只要至少有一个条件满足,就能通过整个测试。仅当两个测试都没有通过时,使用or 的表达式才为False 。
'''
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 or age_1 >= 21
True
>>> age_0 = 18
>>> age_0 >= 21 or age_1 >= 21
False
>>>
'''
'''
5.2.6 检查特定值是否包含在列表中  检查特定值是否包含在列表中
有时候,执行操作前必须检查列表是否包含特定的值。
例如,结束用户的注册过程前,可能需要检查他提供的用户名是否已包含在用户名列表中。
在地图程序中,可能需要检查 用户提交的位置是否包含在已知位置列表中。
 要判断特定的值是否已包含在列表中,可使用关键字in 。
 来看你可能为比萨店编写的一些代码;这些代码首先创建一个列表,
 其中包含用户点的比萨配料,然后检查特定的配料 是否包含在该列表中

'''
'''
requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' in requested_toppings

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

'''

# 5.2.7 检查特定值是否不包含在列表中
# 还有些时候,确定特定的值未包含在列表中很重要;
# 在这种情况下,可使用关键字not in 。
# 例如,如果有一个列表,其中包含被禁止在论坛上发表评论的用户,
# 就可在允许用 户提交评论前检查他是否被禁言:
'''
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ", you can post a response if you wish.")
'''

# 5.2.8 布尔表达式
# 随着你对编程的了解越来越深入,将遇到术语布尔表达式 布尔表达式 ,它不过是条件测试的别名。与条件表达式一样,布尔表达式的结果要么为True ,要么为False 。
# 布尔值通常用于记录条件,如游戏是否正在运行,或用户是否可以编辑网站的特定内容
'''
game_active = True
can_edit = False
'''
# 在跟踪程序状态或程序中重要的条件方面,布尔值提供了一种高效的方式。

# 5.3 理解条件测试后,就可以开始编写if 语句了。if 语句有很多种,选择使用哪种取决于要测试的条件数。前面讨论条件测试时,列举了多个if 语句示例,下面更深入地讨论这个 主题。
# 5.3.1 简单的  简单的if 语句 语句
'''
age = 19
if age >= 18:
    print("You are old enough to vote!")
    print("Have yu registered to vote yet?")
'''
'''
5.3.2   if-else 语句 
语句 经常需要在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作;
在这种情况下,可使用Python提供的if-else 语句。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 turn 18!")
'''
'''
5.3.3 if-elif-else 结构 
经常需要检查超过两个的情形,为此可使用Python提供的if-elif-else 结构。
Python只执行if-elif-else 结构中的一个代码块,
它依次检查每个条件测试,直到遇到通过 了的条件测试。
测试通过后,Python将执行紧跟在它后面的代码,
并跳过余下的测试。
在现实世界中,很多情况下需要考虑的情形都超过两个。
例如,来看一个根据年龄段收费的游乐场:
4岁以下免费; 
4~18岁收费5美元; 
18岁(含)以上收费10美元。 
如果只使用一条if 语句,如何确定门票价格呢?
下面的代码确定一个人所属的年龄段,并打印一条包含门票价格的消息
'''
'''
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.")
'''

# 5.3.4 使用多个elif 代码块
# 可根据需要使用任意数量的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) +".")
'''

# 5.3.6 测试多个条件
'''
if-elif-else 结构功能强大,但仅适合用于只有一个条件满足的情况:
遇到通过了的测试后,Python就跳过余下的测试。这种行为很好,效率很高,
让你能够测试一个特定的 条件。 然而,有时候必须检查你关心的所有条件。
在这种情况下,应使用一系列不包含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("\nFinished making your pizza!")
'''
'''
5.4 使用if 语句处理列表 
通过结合使用if 语句和列表,可完成一些有趣的任务:
对列表中特定的值做特殊处理;高效地管理不断变化的情形,
如餐馆是否还有特定的食材;证明代码在各种情形下都将按 预期那样运行。
'''
'''
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
    print("Adding " + requested_topping + ".")
    print("\nFinished making your pizza!")
'''

'''
5.4.2 确定列表不是空的  确定列表不是空的
到目前为止,对于处理的每个列表都做了一个简单的假设,
即假设它们都至少包含一个元素。我们马上就要让用户来提供存储在列表中的信息,
因此不能再假设循环运行时列表 不是空的。有鉴于此,在运行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?")

'''
5.5 设置if 语句的格式
本章的每个示例都展示了良好的格式设置习惯。
在条件测试的格式设置方面,PEP 8提供的唯一建议是,
在诸如== 、>= 和 <= 等比较运算符两边各添加一个空格,
例如,if age < 4: 要比if age<4: 好。
这样的空格不会影响Python对代码的解读,而只是让代码阅读起来更容易。
'''
'''
5.6 小结  小结 在本章中,你学习了如何编写结果要么为Ture 要么为False 的条件测试。
你学习了如何编写简单的if 语句、if-else 语句和if-elif-else 结构。
在程序中,你使用了这 些结构来测试特定的条件,以确定这些条件是否满足。
你学习了如何在利用高效的for 循环的同时,以不同于其他元素的方式对特定的列表元素进行处理。
你还再次学习了 Python就代码格式方面提出的建议,这可确保即便你编写的程序越来越复杂,
其代码依然易于阅读和理解。 在第6章,你将学习Python字典。字典类似于列表,
但让你能够将不同的信息关联起来。你将学习如何创建和遍历字典,
以及如何将字典同列表和if 语句结合起来使用。学习字典 让你能够模拟更多现实世界的情形。
'''

作业:



# 5-1 条件测试 条件测试 :编写一系列条件测试;将每个测试以及你对其结果的预测和实际结果都打印出来。你编写的代码应类似于下面这样:
'''
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')


food = 'cake'
print("Is food = 'cake'? I predict True")
print(food == 'cake')
print("\nIs food =='fish'? I predict False.")
print(food == 'fish')
'''
'''
5-2 更多的条件测试 更多的条件测试 :你并非只能创建10个测试。如果你想尝试做更多的比较,
可再编写一些测试,并将它们加入到conditional_tests.py中。
对于下面列出的各种测 试,至少编写一个结果为True 和False 的测试。
检查两个字符串相等和不等。 
使用函数lower() 的测试。
检查两个数字相等、不等、大于、小于、大于等于和小于等于。 
使用关键字and 和or 的测试。
测试特定的值是否包含在列表中。
测试特定的值是否未包含在列表中
'''
'''
car = 'bmw'
car == 'audi'
car == 'bmw'
car.lower()
'''
'''
5-3 外星人颜色 外星人颜色#1 :假设在游戏中刚射杀了一个外星人,
# 请创建一个名为alien_color 的变量,并将其设置为'green' 、'yellow' 或'red' 。
# 编写一条if 语句,检查外星人是否是绿色的;如果是,就打印一条消息,指出玩家获得了5个点。
编写这个程序的两个版本,在一个版本中上述测试通过了,
而在另一个版本中未通过(未通过测试时没有输出)。
'''

# alien_color = ['green', 'yellow', 'red']
'''
alien_color = 'green'
if alien_color == 'green':
    print("This player get 5 points")

alien_color = 'yellow'
if alien_color == 'green':
    print("This player get 5 points")
else:
    print("This player get 10 points")
'''
'''
alien_color = 'green'
if alien_color == 'green':
    print("This player get 5 points")
elif alien_color == 'yellow':
    print("This player get 10 points")
else:
    print("This player get 15 points")
'''
'''
alien_color = ['green', 'yellow', 'red']
for i in alien_color:
    if i == 'green':
        print("This color is %s:" % i)
        print("This player get 5 points\n")
    elif i == 'yellow':
        print("This color is %s:" % i)
        print("This player get 10 points\n")
    else:
        print("This color is %s:" % i)
        print("This player get 15 points\n")
'''
'''
5-6 人生的不同阶段 人生的不同阶段 :设置变量age 的值,再编写一个if-elif-else 结构,
根据age 的值判断处于人生的哪个阶段。
如果一个人的年龄小于2岁,就打印一条消息,指出他是婴儿。 
如果一个人的年龄为2(含)~4岁,就打印一条消息,指出他正蹒跚学步。 
如果一个人的年龄为4(含)~13岁,就打印一条消息,指出他是儿童。 
如果一个人的年龄为13(含)~20岁,就打印一条消息,指出他是青少年。 
如果一个人的年龄为20(含)~65岁,就打印一条消息,指出他是成年人。 
如果一个人的年龄超过65(含)岁,就打印一条消息,指出他是老年人。
'''
'''
age = 4

if age <= 2:
    print("This is a Baby")
elif (age >= 2) and (age < 4):
    print("He is following step")
elif (age >= 4) and (age < 13):
    print("He is an children")
elif (age >= 13) and (age < 20):
    print("He is a teenager")
elif (age >= 20) and (age < 65):
    print("He is a adult")
else:
    print("He is an old people")
'''
'''
5-7 喜欢的水果 喜欢的水果 :创建一个列表,其中包含你喜欢的水果,
再编写一系列独立的if 语句,检查列表中是否包含特定的水果。 
将该列表命名为favorite_fruits ,并在其中包含三种水果。 
编写5条if 语句,每条都检查某种水果是否包含在列表中,
如果包含在列表中,就打印一条消息,如“You really like bananas!”。
'''
'''
favorite_fruits = ['apple', 'banana', 'orange']

for favorite_fruit in favorite_fruits:
    if favorite_fruit == 'apple':
        print("This fruit is %s" % favorite_fruit)
        print("You just like %s\n" % favorite_fruit)
    elif favorite_fruit == 'banana':
        print("This fruit is %s" % favorite_fruit)
        print("You really like bananas\n")
    else:
        print("This fruit is %s" % favorite_fruit)
        print("It's just so so\n")

'''
'''
5-8 以特殊方式跟管理员打招呼 以特殊方式跟管理员打招呼 :
创建一个至少包含5个用户名的列表,且其中一个用户名为'admin' 。
想象你要编写代码,在每位用户登录网站后都打印一条问 候消息。
遍历用户名列表,并向每位用户打印一条问候消息。
如果用户名为'admin' ,就打印一条特殊的问候消息,
如“Hello admin, would you like to see a status report?”。
否则,打印一条普通的问候消息,如“Hello Eric, thank you for logging in again”。
'''
'''
admins = ['Maxwell', 'Eve', 'Chris', 'Leon', 'Jack', 'admin']
for admin in admins:
    if admin == 'admin':
        print("Hello admin, would you like to see a status report?")
    else:
        print("Hello %s, thank you for logging in again" % admin)
'''
'''
5-9 处理没有用户的情形 处理没有用户的情形 :在为完成练习5-8编写的程序中,
添加一条if 语句,检查用户名列表是否为空。 
如果为空,就打印消息“We need to find some users!”。
删除列表中的所有用户名,确定将打印正确的消息。
'''
'''
admins = ['Maxwell', 'Eve', 'Chris', 'Leon', 'Jack', 'admin']
if admins:
    for admin in admins:
        if admin == 'admin':
            print("Hello admin, would you like to see a status report?")
        else:
            print("Hello %s, thank you for logging in again" % admin)
else:
    print("We need to find some users")
'''
'''
admins = []
if admins:
    for admin in admins:
        if admin == 'admin':
            print("Hello admin, would you like to see a status report?")
        else:
            print("Hello %s, thank you for logging in again" % admin)
else:
    print("We need to find some users")
'''
'''
5-10 检查用户名 检查用户名 :按下面的说明编写一个程序,
模拟网站确保每位用户的用户名都独一无二的方式。 
创建一个至少包含5个用户名的列表,并将其命名为current_users 。 
再创建一个包含5个用户名的列表,将其命名为new_users ,
并确保其中有一两个用户名也包含在列表current_users 中。 
遍历列表new_users ,对于其中的每个用户名,都检查它是否已被使用。
如果是这样,就打印一条消息,指出需要输入别的用户名;
否则,打印一条消息,指 出这个用户名未被使用。 
确保比较时不区分大消息;换句话说,如果用户名'John' 已被使用,应拒绝用户名'JOHN' 
'''
'''
current_users = ['Maxwell', 'Eve', 'Chris', 'Leon', 'Jack', 'admin']
new_users = ['Tony', 'Nick', 'Mark', 'Leon', 'Jack']
for user in new_users:
    if user in current_users:
        print("This user name %s has been used" % user)
    else:
        print("This user name %s never be named" % user)
'''
'''
5-11 序数 序数 :序数表示位置,如1st和2nd。
大多数序数都以th结尾,只有1、2和3例外。 
在一个列表中存储数字1~9。
遍历这个列表。 在循环中使用一个if-elif-else 结构,
以打印每个数字对应的序数。
输出内容应为1st 、2nd 、3rd 、4th 、5th 、6th 、7th 、8th 和9th ,
但每个序 数都独占一行。
'''
'''
sequence_number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in sequence_number:
    if num == 1:
        print("This sequence is %sst" % num)
    elif num == 2:
        print("This sequence is %snd" % num)
    elif num == 3:
        print("This sequence is %srd" % num)
    elif num == 4:
        print("This sequence is %sth" % num)
    elif num == 5:
        print("This sequence is %sth" % num)
    elif num == 6:
        print("This sequence is %sth" % num)
    elif num == 7:
        print("This sequence is %sth" % num)
    elif num == 8:
        print("This sequence is %sth" % num)
    elif num == 9:
        print("This sequence is %sth" % num)
    else:
        print("This sequence is %sth" % num)
'''
















































































发布了39 篇原创文章 · 获赞 4 · 访问量 3456

猜你喜欢

转载自blog.csdn.net/u011868279/article/details/103224065