第5章 if 语句
第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 语句的更多相关文章
- C++ primer plus读书笔记——第6章 分支语句和逻辑运算符
第6章 分支语句和逻辑运算符 1. 逻辑运算符的优先级比关系运算符的优先级低. 2. &&的优先级高于||. 3. cctype中的函数P179. 4. switch(integer- ...
- C和指针 (pointers on C)——第四章:语句(上)
第四章--语句(上) 总结总结!!! C没有布尔类型,所以在一些逻辑推断时候必须用整型表达式,零值为假,非零值为真. for比while把控制循环的表达式收集起来放在一个地方,以便寻找. do语句比w ...
- python3 第七章 - 循环语句
为了让计算机能计算成千上万次的重复运算,我们就需要循环语句. Python中的循环语句有 while for 循环语句的执行过程,如下图: while 循环 Python中while语句的一般形式: ...
- 《Python学习手册 第五版》 -第10章 Python语句简介
前面在开始讲解数据类型的时候,有说过Python的知识结构,在此重温一下 Python知识结构: 程序由模块组成 模块包含语句 语句包含表达式 表达式创建并处理对象 关于知识结构,前面已经说过我自己的 ...
- C++ Primer Plus 6th 读书笔记 - 第6章 分支语句和逻辑运算符
1. cin读取错误时对换行符的处理 #include <iostream> using namespace std; int main() { double d; char c; cin ...
- 《Python编程从入门到实践》_第五章_if语句
条件测试 每条if语句的核心都是一个值为Ture或False的表达式,这种表达式被称为为条件测试.Python根据条件测试的值为Ture还是False来决定是否执行if语句中的代码.如果条件测试的值为 ...
- Python:从入门到实践--第五章--if语句--练习
#1.编写一系列条件测试:将每个测试以及结果打印出来 car = '宝马' if car == "宝马": print("预测正确") print(car) e ...
- 第五章 if语句
5.2条件测试 使用==判断相当: 使用!=判断不相等: 每条if语句的核心都是一个值为Tre或False的表达式,这种表达式被称为条件测试,如果条件测试的值为Ture,则执行紧跟在if语句后面的代码 ...
- 第五章—if语句
5-1 条件测试 :编写一系列条件测试:将每个测试以及你对其结果的预测和实际结果都打印出来.你编写的代码应类似于下面这样: car = 'subaru' print("Is car == ' ...
随机推荐
- vue同时安装element ui跟 vant
记一个卡了我比较久的问题,之前弄的心态爆炸各种问题. 现在来记录一下,首先我vant是已经安装成功了的. 然后引入element ui npm i element-ui -S 接着按需引入,安装插件 ...
- CF R638 div2 F Phoenix and Memory 贪心 线段树 构造 Hall定理
LINK:Phoenix and Memory 这场比赛标题好评 都是以凤凰这个单词开头的 有凤来仪吧. 其实和Hall定理关系不大. 不过这个定理有的时候会由于 先简述一下. 对于一张二分图 左边集 ...
- 浅谈二分图的最大匹配和二分图的KM算法
二分图还可以,但是我不太精通.我感觉这是一个很烦的问题但是学网络流不得不学它.硬啃吧. 人比较蠢,所以思考几天才有如下理解.希望能说服我或者说服你. 二分图的判定不再赘述一个图是可被划分成一个二分图当 ...
- 4.13 省选模拟赛 树 树形dp 卷积 NTT优化dp.
考试的时候 看到概率 看到期望我就怂 推了一波矩阵树推自闭了 发现 边权点权的什么也不是. 想到了树形dp 维护所有边的断开情况 然后发现数联通块的和再k次方过于困难. 这个时候 应该仔细观察一下 和 ...
- HDU 6787 Chess 2020百度之星 初赛三 T5 题解 dp
传送门:HDU 6787 Chess Problem Description 你现在有一个棋盘,上面有 n 个格子,格子从左往右,1,-,n 进行标号.你可以在棋盘上放置恰好 m 个传送器,并且对于每 ...
- asp.net 远程模型验证
有这样一些场景,我们需要模型验证,某些字段不允许重复,但是又不希望在数据访问层增加一堆额外逻辑判断.我们需要数据访问层简洁,这种模型验证在进去Action之前,验证不通过直接告诉前端. 一个特性,继承 ...
- spring的IOC(反转控制)
Spring概念 1.1.1 spring 是什么 Spring 是分层的 Java SE/EE 应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control:反转控制 ...
- Unity 笔记
摄像机 Main Camera 跟随主角移动,不看 UI 剧情摄像机 当进入剧情时,可以关闭 main camera,启用剧情摄像机,不看 UI UI 摄像机 看 UI Unity编辑器常用的sett ...
- Python 面向对象之高级编程
7.面向对象高级编程 7.1使用__slots__ python动态语言,new 对象后绑定属性和方法 Tip:给一个实例绑定的方法,对其他对象无效.可以通过对class绑定后,所有对象可以调用该方法 ...
- java Iterator迭代器
一 Iterator迭代器概述 java中提供了很多个集合,它们在存储元素时,采用的存储方式不同.我们要取出这些集合 中的元素,可通过一种通用的获取方式来完成. Collection集合元素的通用获取 ...