第5章 if 语句

5.1 一个简单示例

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

①用 if 语句来正确地处理特殊情形。

②检查当前的汽车名是否是 'bmw' ,如行。如果是,就以全大写的方式打印它,如行;否则就以首字母大写的方式打印,如行。

5.2 条件测试

每条 if 语句的核心都是一个值为 True 或 False 的表达式,这种表达式被称为条件测试。

Python根据条件测试的值为 True 还是 False 来决定是否执行 if 语句中的代码。

如果条件测试的值为 True ,Python就执行紧跟在 if 语句后面的代码;如果为 False , Python 就忽略这些代码。

  • 5.2.1 检查是否相等

 car = 'bmw'
print(car == 'bmw')
# True

①相等运算符在它两边的值相等时返回 True ,否则返回 False 。如行

②“=”是赋值符号,“==”是相等运算符。

  • 5.2.2 检查是否相等时不考虑大小写

 car = 'Audi'
print(car == 'audi')
print(car.lower() == 'audi')
print(car)
"""
False
True
Audi
"""

①在Python中检查是否相等时区分大小写。

②但如果大小写无关紧要,而只想检查变量的值,可将变量的值转换为小写,再进行比较。

③lower()方法没有影响存储在变量中的值。

  • 5.2.3 检查是否不相等

 requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")

①要判断两个值是否不等,可结合使用惊叹号和等号( != ),其中的惊叹号表示不。如行

  • 5.2.4 比较数字

 age = 18
print(age == 18)
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
age = 19
print(age < 21)
print(age <= 21)
print(age > 21)
print(age >= 21)
"""
True
That is not the correct answer. Please try again!
True
True
False
False
"""

①“==”可以检查两个数字是否相等。如行

②“!=”可以检查两个数字是否不等。如行

③条件语句中可包含各种数学比较,如小于、小于等于、大于、大于等于。如行7-10

  • 5.2.5 检查多个条件

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

1. 使用 and 检查多个条件

 age_0 = 22
age_1 = 18
print(age_0 >= 21 and age_1 >= 21)
age_1 = 22
print(age_0 >= 21 and age_1 >= 21)
"""
False
True
"""

①要检查是否两个条件都为 True ,可使用关键字 and 将两个条件测试合而为一;如果每个测试都通过了,整个表达式就为 True ;如果至少有一个测试没有通过,整个表达式就为 False 。如行3、5

②为改善可读性,可将每个测试都分别放在一对括号内。

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

2. 使用 or 检查多个条件

 age_0 = 22
age_1 = 18
print(age_0 >= 21 or age_1 >= 21)
age_0 = 18
print(age_0 >= 21 or age_1 >= 21)

①关键字 or 也能够让你检查多个条件,但只要至少有一个条件满足,就能通过整个测试。如行

②仅当两个测试都没有通过时,使用 or 的表达式才为 False 。如行

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

 requested_topping = ['mushrooms', 'onion', 'pineapple']
print('mushrooms' in requested_topping)
# True
print('pepperoni' in requested_topping)
# False

①可使用关键字 in ,来判断特定的值是否已包含在列表中。如行2、4

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

 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.

①可使用关键字 not in ,确定特定的值未包含在列表中。如行

  • 5.2.8 布尔表达式

#布尔表达式 game_active = True can_edit = False

①布尔表达式,它不过是条件测试的别名。与条件表达式一样,布尔表达式的结果要么为 True ,要么为 False 。

 #习题1
ball = 'basketball'
print("Is ball == 'badminton'? I predict True.")
print(ball == 'badminton')
print("Is ball == 'basketball'? I predict False.")
print(ball == 'basketball') flower = 'rose'
print("Is flower == 'rose'? I predict True.")
print(flower == 'rose')
print("Is flower == 'lily'? I predict False.")
print(flower == 'lily') food = 'chocolate'
print("Is food == 'chocolate'? I predict True.")
print(food == 'chocolate')
print("Is food == 'sugar'? I predict False.")
print(food == 'sugar') exercise = 'run'
print("Is exercise == 'walk'? I predict True.")
print(exercise == 'walk')
print("Is exercise == 'run'? I predict False.")
print(exercise == 'run') work = 'programmer'
print("Is work == 'accountant'? I predict True.")
print(work == 'accountant')
print("Is work == 'programmer'? I predict False.")
print(work == 'programmer')
"""
Is ball == 'badminton'? I predict True.
False
Is ball == 'basketball'? I predict False.
True
Is flower == 'rose'? I predict True.
True
Is flower == 'lily'? I predict False.
False
Is food == 'chocolate'? I predict True.
True
Is food == 'sugar'? I predict False.
False
Is exercise == 'walk'? I predict True.
False
Is exercise == 'run'? I predict False.
True
Is work == 'accountant'? I predict True.
False
Is work == 'programmer'? I predict False.
True
"""
#习题2
exercise = 'run'
print(exercise == 'programmer')
print(exercise != 'programmer')
exercise = 'Run'
print(exercise == 'run')
print(exercise.lower() == 'run')
"""
False
True
False
True
"""
car_number = 3
print(car_number > 4)
print(car_number < 4)
print(car_number >= 4)
print(car_number <= 4)
"""
False
True
False
True
"""
car_number = 5
aircraft = 3
print(car_number > 6 and aircraft < 4)
print(car_number >6 or aircraft < 4)
"""
False
True
"""
exercise = ['run', 'walk', 'swim', 'ping-pong', 'basketball']
print('swim' in exercise)
print('swim' not in exercise)
"""
True
False
"""

练习

5.3  if 语句

  • 5.3.1 简单的 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?
"""

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

 if conditional_test:
do something

在第1行中,可包含任何条件测试,而在紧跟在测试后面的缩进代码块中,可执行任何操作。如果条件测试的结果为 True ,Python就会执行紧跟在 if 语句后面的代码;否则Python将忽略这些代码。如行2-4

  • 5.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!
"""

①经常需要在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作;在这种情况下,可使用Python提供的 if-else 语句。 if-else 语句块类似于简单的 if 语句,但其中的 else 语句让你能够指定条件测试未通过时要执行的操作。如行2-7

②if-else 结构非常适合用于要让Python执行两种操作之一的情形。在这种简单的 if-else 结构中,总是会执行两个操作中的一个。

  • 5.3.3  if-elif-else 结构

 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. 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.

①可使用Python提供的 if-elif-else 结构,来检查超过两个的情形。Python只执行if-elif-else 结构中的一个代码块,它依次检查每个条件测试,直到遇到通过了的条件测试。测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的测试。 如行2-7

②代码更简洁,除效率更高外,这些修订后的代码还更容易修改:要调整输出消息的内容,只需修改一条而不是三条 print 语句。如行10-17

  • 5.3.4 使用多个 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.

①可根据需要使用任意数量的 elif 代码块。如行1-10

  • 5.3.5 省略 else 代码块

 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.

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

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

  • 5.3.6 测试多个条件

 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!
"""

①检查你关心的所有条件,使用一系列不包含 elif 和 else代码块的简单 if 语句。在可能有多个条件为 True ,且你需要在每个条件为 True 时都采取相应措施时,适合使用这种方法。

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

 #习题1
alien_color = 'green'
if alien_color == 'green':
print("玩家获得五个点。")
# 玩家获得五个点。
alien_color = 'red'
if alien_color == 'green':
print("玩家获得五个点。") #习题2
alien_color = 'green'
if alien_color == 'green':
print("玩家射杀了绿色外星人,获得五个点!")
else:
print("玩家射杀了非绿色外星人,获得十个点!")
# 玩家射杀了绿色外星人,获得五个点!
alien_color = 'red'
if alien_color == 'green':
print("玩家射杀了绿色外星人,获得五个点!")
else:
print("玩家射杀了非绿色外星人,获得十个点!")
# 玩家射杀了非绿色外星人,获得十个点! #习题3
alien_colors = ['green', 'yellow', 'red']
alien_color = 'yellow'
if alien_color in alien_colors:
if alien_color == 'green':
print("玩家射杀了绿色外星人,获得五个点!")
elif alien_color == 'yellow':
print("玩家射杀了黄色外星人,获得十个点!")
else:
print("玩家射杀了红色外星人,获得十五个点!")
# 玩家射杀了黄色外星人,获得十个点!
alien_colors = ['green', 'yellow', 'red']
alien_color = 'green'
if alien_color in alien_colors:
if alien_color == 'green':
print("玩家射杀了绿色外星人,获得五个点!")
elif alien_color == 'yellow':
print("玩家射杀了黄色外星人,获得十个点!")
else:
print("玩家射杀了红色外星人,获得十五个点!")
# 玩家射杀了绿色外星人,获得五个点!
alien_colors = ['green', 'yellow', 'red']
alien_color = 'red'
if alien_color in alien_colors:
if alien_color == 'green':
print("玩家射杀了绿色外星人,获得五个点!")
elif alien_color == 'yellow':
print("玩家射杀了黄色外星人,获得十个点!")
else:
print("玩家射杀了红色外星人,获得十五个点!")
# 玩家射杀了红色外星人,获得十五个点! #习题4
age = 22
if age < 2:
print("他是婴儿!")
elif age < 4:
print("他正蹒跚学步!")
elif age < 13:
print("他是儿童!")
elif age < 20:
print("他是青少年!")
elif age < 65:
print("他是成年人!")
else:
print("他是老人!")
# 他是成年人! #习题5
favorit_fruits = ['banana', 'apple', 'pineapple']
if 'banana' in favorit_fruits:
print("You really like bananas!")
# You really like bananas!
if 'apple' in favorit_fruits:
print("You really like bananas!")
# You really like bananas!
if 'pineapple' in favorit_fruits:
print("You really like bananas!")
# You really like bananas!
if 'pear' in favorit_fruits:
print("You really like bananas!")
if 'cherry' in favorit_fruits:
print("You really like bananas!")

练习

5.4 使用 if 语句处理列表

  • 5.4.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("\nFinished making your pizza!")
"""
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese. Finished making your pizza!
"""

①可在 for 循环中包含一条 if 语句,来检查特殊元素。如行2-7

  • 5.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?")
# Are you sure you want a plain pizza?

①用if 语句,简单检查,而不是直接执行 for 循环。在 if 语句中将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回 True ,并在列表为空时返回 False 。如行2-7

  • 5.4.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("\nFinished making your pizza!")
"""
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese. Finished making your pizza!
"""

①可使用列表和 if 语句来使用多个列表。如行3-8

 #练习
#习题1
user_names = ['eric', 'lisa', 'bob', 'bub', 'admin']
for user_name in user_names:
if user_name == 'admin':
print("Hello " + user_name + ", would you like to see a status report?")
else:
print("Hello " + user_name + ", thank you for logging in again.")
"""
Hello eric, thank you for logging in again.
Hello lisa, thank you for logging in again.
Hello bob, thank you for logging in again.
Hello bub, thank you for logging in again.
Hello admin, would you like to see a status report?
""" #习题2
user_names1 = ['eric', 'lisa', 'bob', 'bub', 'admin']
user_names = []
if user_names:
for user_name in user_names:
if user_name == 'admin':
print("Hello " + user_name + ", would you like to see a status report?")
else:
print("Hello " + user_name + ", thank you for logging in again.")
else:
print("We need to find some users!") #习题3
current_users = ['eric', 'lisa', 'Bob', 'bub', 'admin']
new_users = ['bob', 'bub', 'ben', 'gill', 'gerry']
for new_user in new_users:
if new_user.lower() in [current_user.lower() for current_user in current_users]:
print(new_user.title() + " has been registered, please enter another username.")
else:
print(new_user.title() + " is not used.")
"""
Bob has been registered, please enter another username.
Bub has been registered, please enter another username.
Ben is not used.
Gill is not used.
Gerry is not used.
""" #习题4
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
if number == 1:
print(str(number) + "st")
elif number == 2:
print(str(number) + "nd")
elif number == 3:
print(str(number) + "rd")
else:
print(str(number) + "th")
"""
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
"""

练习

5.5 设置 if 语句的格式

在条件测试的格式设置方面,PEP 8提供的唯一建议是,在诸如 == 、 >= 和 <= 等比较运算符两边各添加一个空格。

5.6 小结

第5章 if 语句的更多相关文章

  1. C++ primer plus读书笔记——第6章 分支语句和逻辑运算符

    第6章 分支语句和逻辑运算符 1. 逻辑运算符的优先级比关系运算符的优先级低. 2. &&的优先级高于||. 3. cctype中的函数P179. 4. switch(integer- ...

  2. C和指针 (pointers on C)——第四章:语句(上)

    第四章--语句(上) 总结总结!!! C没有布尔类型,所以在一些逻辑推断时候必须用整型表达式,零值为假,非零值为真. for比while把控制循环的表达式收集起来放在一个地方,以便寻找. do语句比w ...

  3. python3 第七章 - 循环语句

    为了让计算机能计算成千上万次的重复运算,我们就需要循环语句. Python中的循环语句有 while for 循环语句的执行过程,如下图: while 循环 Python中while语句的一般形式: ...

  4. 《Python学习手册 第五版》 -第10章 Python语句简介

    前面在开始讲解数据类型的时候,有说过Python的知识结构,在此重温一下 Python知识结构: 程序由模块组成 模块包含语句 语句包含表达式 表达式创建并处理对象 关于知识结构,前面已经说过我自己的 ...

  5. C++ Primer Plus 6th 读书笔记 - 第6章 分支语句和逻辑运算符

    1. cin读取错误时对换行符的处理 #include <iostream> using namespace std; int main() { double d; char c; cin ...

  6. 《Python编程从入门到实践》_第五章_if语句

    条件测试 每条if语句的核心都是一个值为Ture或False的表达式,这种表达式被称为为条件测试.Python根据条件测试的值为Ture还是False来决定是否执行if语句中的代码.如果条件测试的值为 ...

  7. Python:从入门到实践--第五章--if语句--练习

    #1.编写一系列条件测试:将每个测试以及结果打印出来 car = '宝马' if car == "宝马": print("预测正确") print(car) e ...

  8. 第五章 if语句

    5.2条件测试 使用==判断相当: 使用!=判断不相等: 每条if语句的核心都是一个值为Tre或False的表达式,这种表达式被称为条件测试,如果条件测试的值为Ture,则执行紧跟在if语句后面的代码 ...

  9. 第五章—if语句

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

随机推荐

  1. pdb 进行调试

    import pdb a = 'aaa' pdb.set_trace( ) b = 'bbb' c = 'ccc' final = a+b+c print(final) import pdb a = ...

  2. Python实现微信读书辅助工具

    [TOC] ##项目来源 这个有意思的项目是我从GitHub上找来的,起因是在不久前微信读书突然就设置了非会员书架数目上限,我总想做点什么来表达我的不满,想到可否用爬虫来获取某一本书的内容, 但是我技 ...

  3. Spring中使用MyBatis Generator

    简介 MyBatis Generator 是由MyBatis官方提供的MyBatis代码生成器.可以根据数据库表生成相关代码,比如POJO.Mapper接口.SQL Map xml等. 使用方式 MB ...

  4. 移动端与Web端疫情数据展示

    1.题目要求 2.整体思想 首先是在前两阶段已经完成的echarts可视化.利用Jsoup爬取疫情数据基础上来进行调用与完善.大致思想是在Android Studio上完成交互去调用ecplise中的 ...

  5. tomcat启动失败的解决办法

    初次安装tomcat启动失败的解决办法: 1.CATALINA_HOME    C:\Program Files\apache-tomcat-8.5.242.path  %CATALINA_HOME% ...

  6. RabbitMQ 基础概念进阶

    上一篇 RabbitMQ 入门之基础概念 介绍了 RabbitMQ 的一些基础概念,本文再来介绍其中的一些细节和其它的进阶的概念. 一.消息生产者发送的消息不可达时如何处理 RabbitMQ 提供了消 ...

  7. C#LeetCode刷题-队列

    队列篇 # 题名 刷题 通过率 难度 363 矩形区域不超过 K 的最大数值和   27.2% 困难 621 任务调度器   40.9% 中等 622 设计循环队列 C#LeetCode刷题之#622 ...

  8. C#设计模式之13-职责链模式

    职责链模式(Chain of Responsibility Pattern) 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archive ...

  9. day4 列表 字典 元组

      元组  不能修改里面的数据       字典是无序的集合  通过键名来访问元素       列表是有有序的  通过下标来访问    可以进行修改       列表  []   是python中使用 ...

  10. Git的使用方法及IDEA与Git的集成

    一.Git的环境配置 1.Git软件下载 (下载地址:https://git-scm.com/)由于国外的网站下载的超慢可以使用国内的阿里的开源镜像下载(下载地址:https://npm.taobao ...