第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. PHP入门之函数

    前言 之前对PHP的类型.运算符和流程控制简单说了一下.想了解的,这是地址. PHP入门之类型与运算符 PHP入门之流程控制 下面对函数简单说一下. 函数的基本概念 为完成某一个功能的程序指令的合集, ...

  2. Springboot+Mybatis+Clickhouse+jsp 搭建单体应用项目(一)

    一.服务器安装clickhouse服务 参阅 :https://www.cnblogs.com/liuyangfirst/p/13379064.html 二.连接数据库 成功 三.新建库 CREATE ...

  3. PHP array_diff_key() 函数

    实例 比较两个数组的键名,并返回差集: <?php $a1=array("a"=>"red","b"=>"gre ...

  4. Python File readline() 方法

    概述 readline() 方法用于从文件读取整行,包括 "\n" 字符.如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符.高佣联盟 w ...

  5. C/C++编程笔记:C语言入门知识点(一),请收藏C语言最全笔记!

    C语言简介 C 语言是一种通用的高级语言,最初是由丹尼斯·里奇在贝尔实验室为开发 UNIX 操作系统而设计的.C 语言最开始是于 1972 年在 DEC PDP-11 计算机上被首次实现. 原文链接: ...

  6. SpringBoot 发送邮件和附件

    作者:yizhiwaz 链接:www.jianshu.com/p/5eb000544dd7 源码:https://github.com/yizhiwazi/springboot-socks 其他文章: ...

  7. 【mysql数据库基础】

    基础:·数据库的本质是一个文件·行---记录·列---字段·RDBMS是一个程序·SQL是结构化的查询语言·MYSQL是一个数据库软件,可以通过SQL操作MYSQL数据库·SQL语句不区分大小写·学了 ...

  8. Android——对话框的全部内容。(课堂总结)

    前面的总结是写过对话框的,但是那只是冰山一角,简单的创建和使用罢了. 今天具体讲下AlertDialog. 首先对话框不需要在布局里写,在活动里new出来的. AlertDialog.Builder ...

  9. CI4框架应用六 - 控制器应用

    这节我们来分析一下控制器的应用,我们看到系统提供的控制器都是继承自一个BaseController,我们来分析一下这个BaseController的作用 use CodeIgniter\Control ...

  10. JS解密入门——有道翻译

    JS解密入门——有道翻译 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做案例的人,却不知道如何去学习更加高深的知识.那么针对这 ...