python中的if语句

本文详细介绍了Python中的条件测试,包括检查相等、不相等、数值比较、多个条件、列表中值的包含与排除以及布尔表达式。接着讲解了if语句的使用,从简单的if到if-else、if-elif-else结构,以及在处理列表时的应用,如检查特殊元素、列表是否为空和使用多个列表。最后强调了if语句的格式规范,以提高代码可读性。
摘要由CSDN通过智能技术生成

目录

一、条件测试

二、if语句

三、使用if语句处理列表

四、设置if语句的格式


cars=['audi','bwm','subaru','toyata']
for car in cars:
	if car == 'bwm':
		print(car.upper())
	else:
		print(car.title())
Audi
BWM
Subaru
Toyata

一、条件测试

每条if语句的核心都是一个值为True或False的表达式,这种表达式称为条件测试。python根据条件测试的值为True或False来判断是否执行if语句中的代码。若为True,则执行紧跟在if语句后的代码;若为False,则忽略这些代码。

1.检查是否相等

将一个变量的当前值和特定值进行比较,相等运算符==在两边的值相等时返回True,否则为False.一个等号为陈述,两个等号为发问

>>> car='bmw'  #使用一个等号 将car的值设置为'bmw'
>>> car == 'bmw' #使用两个等号 检查car的值是否为'bmw'
True

2.检查是否相等时忽略大小写

两个大小写不同的值被视为不相等

>>> car='Audi'
>>> car == 'audi'
False

若大小写无关紧要,可将变量的值转为小写。运用方法lower,这样的比较不会影响原来的变量。网站可使用类似测试来确保用户名独一无二,而并非只是与另一个用户名的大小写不同。

>>> car='Audi'            #将'Audi'的值赋给变量car
>>> car.lower()=='audi'   #获取变量的值将其转为小写,再将结果与字符串'audi'比较
True
>>> car
'Audi'

3.检查是否不相等

判断两个值是否不等,可结合惊叹号和等号 (!=),其中!表示不。大多数情况下检查两个值是否相等,有时检查两个值是否不等效率会更高。

requested_topping='mushrooms'
if requested_topping != 'anchovies': #requested_topping的值与anchovies比较,不等才会执行后面代码
	print("Hold the anchovies!")
Hold the anchovies!

4.数值比较

判断是否相等,不等,数学比较(如<、<=、>、>=)

>>> age='18'
>>> age == '18'
True
answer=17
if answer != 47:
	print("This is not the correct answer,try again!")
This is not the correct answer,try again!
>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False

5.检查多个条件

有时需要两个条件为True才能执行相应操作,有时只要一个条件为True

1.用关键字and检查多个条件,要检查两个条件是否为True,可用关键词and将两个条件测试合二为一。为改善可读性,可将每个测试分别放在一对圆括号( )内,但非必须。

>>> age_0 = 22
>>> age_1 = 18
>>> age_0 > 21 and age_1 > 21
False
>>> age_1 = 23
>>> age_0 > 21 and age_1 > 21
True
>>> (age_0 > 21) and (age_1 > 21)
True

2.用关键字or检查多个条件,至少一个条件满足,就能通过整个测试

>>> 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(f"{user.title()}, you can post a response if you wish.")
Marie, you can post a response if you wish.

8.布尔表达式

条件测试的别名,与条件表达式一样,布尔表达式的结果为True 或False。可直接在print中判断

car='subaru'
print("Is car == 'subaru'?I predict True.")
print(car == 'subaru')
print("Is car == 'audi'?I predict False.")
print(car == 'audi')
Is car == 'subaru'?I predict True.
True
Is car == 'audi'?I predict False.
False

二、if语句

1.简单的if 语句

只包含一个测试和一个操作。在if语句中,若测试通过了,将执行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?

2.if-else语句

在条件测试通过时,执行一个操作;在没有通过时,执行另一个操作。非常适合执行两种操作之一。注意: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.if-elif-else结构

检查超过两个的情形,python只执行if-elif-else结构中的一个代码块,依次检查每个条件测试,直到通过。通过后,python执行紧跟在其后的代码,并跳过余下测试。

age = 12
if age < 4:
	print("Your addmission cost is $0.")
elif age<18:
	print("Your addmission cost is $25.")
else:
	print("Your addmission cost is $40.")
Your addmission cost is $25.

更简洁的代码,只确定门票价格,而不是在同一时间打印消息。也更便于方便修改。 不同的思维方式

age = 12
if age < 4:
	price = 0
elif age < 18:
	price = 25
else:
	price = 40
print(f"Your addmision cost is ${price}.")

4.使用多个elif代码块

可根据需要使用任意数量的elif代码块。

age = 12
if age < 4:     #4岁以下门票为0
	price = 0
elif age < 18:  #18岁以下门票为25
	price = 25
elif age < 65:  #65岁以下门票为40
	price = 40
else:         #65岁以上门票为20,注:依次检查,只执行结构中一个代码块
	price = 20
print(f"Your addmision cost is ${price}.")
Your addmision cost is $25.

5.省略else代码块

python并不要求if-elif结构后面必须有else代码块。有时,else代码块有用,有时,使用一条elif语句更清晰。else是一条包罗万象的语句,只要不满足if或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 addmision cost is ${price}.")

6.测试多个条件

if-elif-else结构功能强大,但python遇到通过的测试后,就会跳过余下的测试。如果只想执行一个代码块,就使用if-elif-else结构;如果要执行多个代码块,就使用一系列独立的if语句

requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
	print("Adding mushrooms.")
if 'pepperoni' in requested_toppings: #这是一个if语句,不管前一个测试是否通过,都将进行这个测试
	print("Adding pepperoni.")
if 'extra cheese' in requested_toppings: #不管前两个测试结果如何,都会执行这个代码
	print("Adding extra cheese.")
#程序运行时,会执行这三个独立的测试。
print("Finished making your pizza!")
Adding mushrooms.
Adding extra cheese.
Finished making your pizza!

三、使用if语句处理列表

1.检查特殊元素

requested_toppings = ['mushrooms','green pepers','extra cheese']
for requested_topping in requested_toppings:
	print(f"Adding {requested_topping}")
print("Finished making your pizza!")
Adding mushrooms
Adding green pepers
Adding extra cheese
Finished making your pizza!

用一个for循环进行了简单的输出。但如果店里的青椒用完了,可在for循环中添加一条if-else语句

requested_toppings = ['mushrooms','green pepers','extra cheese']
for requested_topping in requested_toppings:
	if requested_topping == 'green pepers':
		print("Sorry,we are out of green peper right now.")
	else:
		print(f"Adding {requested_topping}")
print("Finished making your pizza!")
Adding mushrooms
Sorry,we are out of green peper right now.
Adding extra cheese
Finished making your pizza!

2.确定列表不是空的

运行for循环前列表是否为空很重要。先用if+变量名来判断列表中是否有元素。if语句中将列表名作条件表达式时,若列表中包含元素则返回True,若列表为空则返回False。

requested_toppings = []
if requested_toppings:  #if语句中将列表名作条件表达式时,列表中包含元素时为True,为空时返False.
	for requested_topping in requested_toppings:
		print(f"Adding {requested_topping}.")
else:
	print("Are you sure you want a plain pizza?")
Are you sure you want a plain pizza?

3.使用多个列表

available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
requested_toppings = ['mushrooms','frensh 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 frensh fries.
Adding extra cheese.

for和if的搭配更高效,当if用于两个列表中,用for循环遍历其中的一个列表转为一个个元素。

判断列表中是否有元素:if+列表名,若有元素执行接下来的操作,若无执行else.

四、设置if语句的格式

在条件测试的格式上,==、>=、<= 等比较运算符两边各添加一个空格,让代码读起来更容易。

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值