文章目录
本帖将学习条件测试,学习if语句在Python中的用法以及作用。
1 简单示例
此示例中if语句将用于处理编程过程中的特殊情况。比如一个汽车列表,你想将所有汽车名都以首字母大写的方式打印出来,这个可以运用之前学习的for循环,但是其中有一个特殊的汽车名“bmw”需要以全大写的方式打印出来,这时就需要使用if语句来特殊处理。
cars=['audi','bwm','subaru','toyota']
for car in cars:
if car=='bwm':#检查汽车名是否为bwm
print(car.upper())#如果是则以全大写的方式打印出来
else:
print(car.title())#如果不是则以首字母大写的方式打印出来
#打印结果
Audi
BWM
Subaru
Toyota
2 条件测试
2.1 检查是否相等
检查是否相等就如同例1中的一样。判断之后返回true或者false。其中需要记得的是一个“=”表示陈述,即赋值,两个“==”表示发问,即判断是否相等。
检查是否相等时要考虑首字母的大小写,如果大小写不同,则会被视为不相等。
2.2 检查是否不相等
判断两个值是否不相等,使用!=,下例将教会我们如何使用不等运算符:
requested_topping='mushrooms'
if requested_topping !='anchovies':
print("Hold the anchovies!")
#打印输出
Hold the anchovies!
2.3 比较数字
2.4 检查多个条件
如果想同时检查多个条件,就可以使用and和or来实现
1.使用and来检查多个条件
我们筛选出年满18周岁的公民:
2.使用or来检查多个条件
其中有一个人年满18周岁即可:
2.5 检查特定值是否包含于列表中
2.6 检查特定值不包含于列表中
2.7 布尔表达式
布尔值通常用于记录条件,如游戏是否正在运行,或用户是否可以编辑网站的特定内容。
下例为简单的布尔表达式写法:
game_active=True
can_edit=False
3 编写if语句
if语句有很多种,要根据测试的条件数来确定使用哪种if语句。
3.1 简单的if语句
最简单的if语句只有一个测试和一个操作,基本格式如下:
if conditional_test:#指定测试条件
do something#若上述结果返回为true则执行if语句后面的内容,否则将忽略该内容
举个简单的例子:
age=19
if age>=18:
print("You are old enough to vote!")#在if语句中缩进的作用与for循环后面的缩进作用相同
#if 语句后可跟多行代码
#打印结果
You are old enough to vote!
3.2 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!
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) + ".")#只在条件测试结束后执行一次
#打印结果与上述结果一致
除此之外,根据需要可使用多个elif代码块,比如上述例子中再加入一个条件,要求65岁以上老人也半价,则代码为:
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) + ".")#只在条件测试结束后执行一次
在Python中某些情况下else代码块可以省略,而选择用elif来实现,这样使得目的更加明确:
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) + ".")#只在条件测试结束后执行一次
4 使用if语句处理列表
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!
4.2 确定列表不为空
requested_toppings = []#创建一个不包含任何配料的空列表
if requested_toppings:#在列表至少包含一个元素时返回true,列表为空返回False
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?
4.3 使用多个列表
下面的示例定义了两个列表,其中第一个列表包含比萨店供应的配料,而第二个列表包含顾客点的配料。这次对于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("Adding " + requested_topping + ".")
else:#若没有则执行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!
本文结束,谢谢阅读,后续会接着更新Python入门学习知识,敬请观看,谢谢!!!
参考书籍:《Python编程从入门到实践》