一、一个简单示例

  假设有一个汽车列表,并想将其每辆汽车的名称打印出来。遇到汽车名‘bmw’,以全大写打印;其他汽车名,首字母大写

cars=['audi','bmw','subaru','toyota']
for car in cars:
if car == 'bmw': #检查汽车名是否是bmw
print(car.upper())
else:
print(car.title()) #输出结果:
Audi
BMW
Subaru
Toyota

二、条件测试

if 语句的核心都有一个值为True或False的表示式。如果条件测试的值为True,就执行if 语句后面的代码;如果为False,就忽略这些代码。

1. 检查是否相等

>>>car = 'bmw'    #将car的值设置为bmw
>>>car =='bmw' #使用两个等号检查car的值是否为bmw。如果是,返回True;如果不是,返回False
  True

2. 检查是否等于时不考虑大小写:python检查是否等于时区分大小写

>>>car = 'Audi'             #将Audi存储在变量car中
>>>car.lower()=='audi' #获取变量car的值并将其转换为小写,再将结果与字符串‘audi’进行比较。
True
>>>car
'Audi' #这个条件测试并没有影响存储在变量car中的值

3. 检查是否不相等:用(!=)来判断两个值是否不等

requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
#输出结果:
Hold the anchovies!

4. 比较数字

>>>age = 18
>>>age == 18
True #比较相等,返回True answer = 17
if answer !=42: #判断两个数字是否不等,如不等打印下面消息
print("That is not the correct answer.Please try again!") >>>age = 19
>>>age < 21
True
>>>age <=21
True
>>>age > 21
False
>>>age >=21
False

5. 检查多个条件  

a. 使用and检查多个条件:检查两个条件是否都为True,如果是,整个表达式为True;反之如果有一方不是True,整个表达式就为False。

>>>age_0 = 22         #定义变量age_0和age_1
>>>age_1 =18
>>>age_0 >=21 and age_1 >=21 #检查这两个变量是否都大于或等于21
False # 两个变量有一个不符合条件,表达式结果为False
>>>age_1 =22 #把age_1的的值修改之后,符合条件,表达式结果为True
>>>age_0 >=21 and age_1 >=21
True

b. 使用 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

6. 检查特定值是否包含在列表中:要判断特定的值是否已包含在列表中,使用关键字 in。

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

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.")
#输出结果:Marie, you can post a response if you wish.
# user的值未包含在列表banned_users中,python将返回True,进而执行缩进的代码行

8. 布尔表达式:与条件表达式一样,结果不是True,就是False

game_active = True
can_edit = False #布尔值通常用于记录条件,如游戏是否正在运行,或用户是否可以编辑网站的特定内容

  

三、if 语句

1. 简单的if 语句:在if 语句中,缩进的作用域for 循环相同。如果测试通过,将执行 if 语句后面所有缩进的代码行,否则将忽略。

if conditional_test:     #conditional_test:可包含任何条件测试
do something #条件为True,执行此代码块;条件为False,不执行此代码块
例如:
age = 19
if age >= 18:
   print("You are old enough to vote!")
#输出结果:
You are old enough to vote!

2. if-else 语句:条件测试通过执行一个操作,没有通过执行另一个操作。

age = 17
if age >= 18: # 条件不通过,执行else的语句块
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vate.")
print("Please register to vote as soon as you turn 18!")
#输出结果:
Sorry, you are too young to vate.
Please register to vote as soon as you turn 18!

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")
或简易代码如下,此代码中if-elif-else中的作用减弱,但调整价格方面变简易了:
age = 12
if age <4:
  price= 0
elif age < 18:
  price= 5
else:
  price= 10
print("You admission cost is $"+ str(price) + ".")
#输出结果:Your admission cost is $5

4. 使用多个elif 代码块

age = 66
if age <4:
price = 0
elif age < 18:
price = 5
elif age <65:
price = 10
else:
price = 5
print("You admission cost is $"+ str(price) + ".") #输出结果:You admission cost is $5.

5. 省略else 代码块:部分情况下,使用一条elif 语句处理特定的情形更清晰,所以需要省略 else 代码块。

age = 66
if age <4:
price = 0
elif age < 18:
price = 5
elif age <65:
price = 10
elif age >=65:
price = 5
print("You admission cost is $"+ str(price) + ".")
#输出结果:You admission cost is $5.

6. 测试多个条件

requested_topping = ['mushrooms','extra cheese']
if 'mushrooms' in requested_topping:
print("Adding mushrooms")
if 'pepperoni' in requested_topping:
print("Adding pepperoni")
if 'extra cheese' in requested_topping:
print("Adding extra cheese")
print("\nFinished making your pizza!") #输出结果:
Adding mushrooms
Adding extra cheese Finished making your pizza!

 解析以上代码:

a. 创建一个列表,包含顾客点的配料

b. if 语句检查配料是mushrooms 或 extra cheese 或 pepperoni。这三个if 语句块是独立的测试,就是不会因为前面测试通过而跳出其余的代码块,如果后面的代码块也通过,会继续执行。也就是多重选择,多重结果。

四、使用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("\nFinished making your pizza!") #输出结果:
Addingmushrooms.
Sorry, we are out of green peppers right now.
Addingextra cheese. Finished making your pizza!

 解析以上代码:

a. 创建一个列表,包含三种配料

b. for循环语句来依次添加列表中的配料。先检查顾客点的是否是green peppers,如果是,就打印一条消息告知不能点green peppers。else代码块确保其他配料都添加到披萨中。

c. 添加完成之后,打印一条消息告知顾客配料已经添加完成

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?

 解析以上代码

a. 创建一个空列表

b. 用if 进行检查,如果变量在列表中,执行if 后面的 for 循环语句依次进行配料的添加

c 用if 进行检查,如果变量不在列表中,就打印询问顾客是否要点不加任何配料的披萨

3. 使用多个列表

available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
requested_toppings = ['mushrooms','frenche 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!") #输出结果:
Addingmushrooms.
Sorry, we don't havefrenche fries.
Addingextra cheese. Finished making your pizza!

 解析以上代码:

a. 先定义两个列表,第一个列表包含披萨店供应的配料,第二个列表包含顾客点的配料

b. 用for 循环遍历顾客点的配料列表:检查配料是否包含在供应的配料列表中

c. 用 if 判断如果顾客要求的配料在供应配料列表中,就执行if 后面的代码块

d. 用 if 判断如果顾客要求的配料不在供应配料列表中,就执行 else 后面的代码块

e. 添加完成之后,最后打印告知用户披萨已经完成

五、设置 if 语句的格式:在==、>=和 <=等比较运算符两边各添加一个空格,代码阅读就更简易。

备注:内容摘录自《python编程:从入门到实践》

python编程:从入门到实践----第五章>if 语句的更多相关文章

  1. #Python编程从入门到实践#第四章笔记

    #Python编程从入门到实践#第四章笔记   操作列表 ​​​1.遍历列表 使用for循环,遍历values列表 for value in values: print(value) 2.数字列表 使 ...

  2. 《Python编程从入门到实践》第二章_变量和简单数据类型

    什么是变量呢? 举例: >>> message = "Hello,Python!" >>> print (message) Hello,Pyth ...

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

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

  4. #Python编程从入门到实践#第三章笔记

      列表简介 ​​​1.什么是列表 列表:由一系列按也顶顺序排列的元素组成.元素之间可以没有任何关系. 列表:用方括号[]表示,并用逗号分隔其中元素.名称一般为复数 2.访问元素 (1)列表是有序集合 ...

  5. Python编程从入门到实践笔记——异常和存储数据

    Python编程从入门到实践笔记——异常和存储数据 #coding=gbk #Python编程从入门到实践笔记——异常和存储数据 #10.3异常 #Python使用被称为异常的特殊对象来管理程序执行期 ...

  6. Python编程从入门到实践笔记——文件

    Python编程从入门到实践笔记——文件 #coding=gbk #Python编程从入门到实践笔记——文件 #10.1从文件中读取数据 #1.读取整个文件 file_name = 'pi_digit ...

  7. Python编程从入门到实践笔记——类

    Python编程从入门到实践笔记——类 #coding=gbk #Python编程从入门到实践笔记——类 #9.1创建和使用类 #1.创建Dog类 class Dog():#类名首字母大写 " ...

  8. Python编程从入门到实践笔记——函数

    Python编程从入门到实践笔记——函数 #coding=gbk #Python编程从入门到实践笔记——函数 #8.1定义函数 def 函数名(形参): # [缩进]注释+函数体 #1.向函数传递信息 ...

  9. Python编程从入门到实践笔记——用户输入和while循环

    Python编程从入门到实践笔记——用户输入和while循环 #coding=utf-8 #函数input()让程序暂停运行,等待用户输入一些文本.得到用户的输入以后将其存储在一个变量中,方便后续使用 ...

随机推荐

  1. 关于springmvc的消息转换器

    之前有用到消息转换器,一直是配置configureMessageConverters()这个方法的,虽然知道也有extendMessageConverters().它们的区别的是第一个不会继承框架默认 ...

  2. 【剑指Offer】面试题09. 用两个栈实现队列

    题目 用两个栈实现一个队列.队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能.(若队列中没有元素,delete ...

  3. docker - how do you disable auto-restart on a container?

    https://stackoverflow.com/questions/37599128/docker-how-do-you-disable-auto-restart-on-a-container 9 ...

  4. PAT Advanced A1021 Deepest Root (25) [图的遍历,DFS,计算连通分量的个数,BFS,并查集]

    题目 A graph which is connected and acyclic can be considered a tree. The height of the tree depends o ...

  5. vue中的axios请求

    1.get请求 // get this.$axios.get('请求路径') .then(function (response) { console.log(response); // 成功 }) . ...

  6. [GXYCTF2019]BabySQli

    0x00 知识点 emmm这道题目就是脑洞得大,能猜后端源码 0x01 解题 查看源码: base32,base64解码得到 select * from user where username = ' ...

  7. 面试题:你使用过concurrent包下的那些类?

    1.executor接口,使用executor接口的子接口ExecutorService用来创建线程池2.Lock接口下的ReentrantLock类,实现同步,比如三个线程循环打印ABCABCABC ...

  8. List、Set和Map详解及其区别和他们分别适用的场景

    Java中的集合包括三大类 它们是Set(集).List(列表)和Map(映射),它们都处于java.util包中,Set.List和Map都是接口,它们有各自的实现类.Set的实现类主要有HashS ...

  9. js 关联数组

    踩得坑: JS ,通过 new Array()创建了一个数组: var param =  new Array();param["key1"] = value1;param[&quo ...

  10. iOS 中的延时操作方法

    1. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_q ...