python 学习之 if 语句
人性本贪婪

1引言
与 R 语言里面类似, if 语句 用来批量处理数据。
2简单示例
下面的代码遍历这个列表,并以首字母大写的方式打印其中的汽车名,不过对于’bmw’ ,则以全大写的方式打印:
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
Audi
BMW
Subaru
Toyota
3条件测试
每条 if 语句的核心都是一个值为 True 或 False 的表达式,这种表达式称为条件测试 。Python 根据条件测试的值为 True 还是 False 来决定是否执行 if 语句中的代码。如果条件测试的值为 True ,Python 就执行紧跟在 if 语句后面的代码;如果为 False ,Python 就忽略这些代码。
检查是否相等
大多数条件测试将一个变量的当前值同特定值进行比较。最简单的条件测试检查变量的值是否与特定值相等:
car = 'bmw'
car == 'bmw'
True
如果变量 car 的值不是’bmw’ ,上述测试将返回 False 。
检查是否相等时忽略大小写
在 Python 中检查是否相等时区分大小写。例如,两个大小写不同的值被视为不相等:
car = 'Audi'
car == 'audi'
False
如果大小写很重要,这种行为有其优点。但如果大小写无关紧要,只想检查变量的值,可将变量的值转换为小写,再进行比较:
car = 'Audi'
car.lower() == 'audi'
True
检查是否不相等
要判断两个值是否不等,可结合使用惊叹号和等号( != ),其中的惊叹号表示不 ,其他很多编程语言中也是如此:
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
Hold the anchovies!
数值比较
条件语句中可包含各种数学比较,如小于、小于等于、大于、大于等于:

检查多个条件
你可能想同时检查多个条件。例如,有时候需要在两个条件都为 True 时才执行相应的操作,而有时候只要求一个条件为 True 。在这些情况下,关键字 and 和 or 可助你一臂之力。
使用 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
使用 or 检查多个条件:
关键字 or 也能够让你检查多个条件,但只要至少一个条件满足,就能通过整个测试。仅当两个测试都没有通过时,使用 or 的表达式才为 False :
age_0 = 22
age_1 = 18
age_0 >= 21 or age_1 >= 21
True
age_1 = 22
age_0 >= 21 or age_1 >= 21
True
检查特定值是否包含在列表中
要判断特定的值是否已包含在列表中,可使用关键字 in 。下面来看看你可能为比萨店编写的一些代码。这些代码首先创建一个列表,其中包含用户点的比萨配料,然后检查特定的配料是否包含在该列表中:
requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' in requested_toppings
True
'pepperoni' in requested_toppings
False
检查特定值是否不包含在列表中
还有些时候,确定特定的值未包含在列表中很重要。在这种情况下,可使用关键字not in :
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(f"{user.title()}, you can post a response if you wish.")
Marie, you can post a response if you wish.
4if 语句
简单的 if 语句
最简单的 if 语句只有一个测试和一个操作:
age = 19
if age >= 18:
print("You are old enough to vote!")
You are old enough to vote!
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!")
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
if-elif-else 结构
我们经常需要检查超过两个的情形,为此可使用 Python 提供的 if-elif-else 结构。Python 只执行 if-elif-else 结构中的一个代码块。它依次检查每个条件测试,直到遇到通过了的条件测试。测试通过后,Python 将执行紧跟在它后面的代码,并跳过余下的测试:
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $25.")
else:
print("Your admission cost is $40.")
Your admission cost is $25.
使用多个 elif 代码块
可根据需要使用任意数量的 elif 代码块:
age = 50
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
else:
price = 20
print(f"Your admission cost is ${price}.")
Your admission cost is $40.
省略 else 代码块
Python 并不要求 if-elif 结构后面必须有 else 代码块。在有些情况下,else 代码块很有用;而在其他一些情况下,使用一条 elif 语句来处理特定的情形更清晰:
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
elif age >= 65:
price = 20
print(f"Your admission cost is ${price}.")
Your admission cost is $25.
5使用 if 语句处理列表
通过结合使用 if 语句和列表,可完成一些有趣的任务:对列表中特定的值做特殊处理;高效地管理不断变化的情形。
检查特殊元素
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(f"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!
确定列表不是空的
在 if 语句中将列表名用作条件表达式时,Python 将在列表至少包含一个元素时返回 True ,并在列表为空时返回 False:
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print(f"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?
使用多个列表
下面的示例定义了两个列表,其中第一个列表包含比萨店供应的配料,而第二个列表包含顾客点的配料。这次对于 requested_toppings 中的每个元素,都检查它是否是比萨店供应的配料,再决定是否在比萨中添加它:
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(f"Adding {requested_topping}.")
else:
print(f"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 语句的格式
本章的每个示例都展示了良好的格式设置习惯。在条件测试的格式设置方面,PEP 8 提供的唯一建议是,在诸如== 、>= 和<= 等比较运算符两边各添加一个空格:
if age < 4: # 好
if age<4: # 次于上者

欢迎加入生信交流群。加我微信我也拉你进 微信群聊 老俊俊生信交流群
哦,数据代码已上传至QQ群,欢迎加入下载。
群二维码:

老俊俊微信:
知识星球:
所以今天你学习了吗?
欢迎小伙伴留言评论!
今天的分享就到这里了,敬请期待下一篇!
最后欢迎大家分享转发,您的点赞是对我的鼓励和肯定!
如果觉得对您帮助很大,赏杯快乐水喝喝吧!
往期回顾
◀…
请关注“恒诺新知”微信公众号,感谢“R语言“,”数据那些事儿“,”老俊俊的生信笔记“,”冷🈚️思“,“珞珈R”,“生信星球”的支持!