《Python编程从入门到实践》
第五章 if语句
零. 实例引入
简单实例,理解语法,注意缩进。不同于C语言if(),这里if+判别语句 :(冒号不要丢了!!)else :(也需要冒号)
competitors=["jacklove",'theshy','Feaker',"Rookie"]
for x in competitors:
if x == 'theshy':
print(x.title())
else:
print(x)
jacklove
Theshy
Feaker
Rookie
①. 条件测试
这一部分内容是用Python自带的Shell编辑器的,原理很好懂,看书即可。不做赘述。
关键字in让Python检查某元素是否在列表里。not in 就是不在咯
>>> age_1=12
>>> age_2=24
>>> age_1<=20 and age_2>=20
True
>>> age_1=12
>>> age_2=24
>>> age_1<=10 or age_2>=20
True
>>> competitors=["jacklove",'theshy','Feaker',"Rookie"]
>>> 'theshy'in competitors
True
competitors=["jacklove",'theshy','Feaker',"Rookie"]
if 'uzi'.title() not in competitors:
print('uzi'.title()+" "+'is not in competitors'+'.')
Uzi is not in competitors.
2. if语句
缩进十分重要!! 如果if判断的条件为真,执行所有缩进的代码行。反之,忽略所有。
if-else语句 , if-elif-else语句,if-elif-elif-…语句。类似于分段函数的分段区间,在不互通的判断条件下,执行不同的语句。结束不带else(省略else的代码块)的好处很明显,不会判别与所给条件以外的其他值。
age =18
if age<10:
print("Sorry,you are too young.")
elif age>=18:
print("You can come in.")
You can come in.
易错:测试多个条件
competitors=["jacklove",'theshy','Feaker',"Rookie"]
if 'jacklove' in competitors:
print(competitors[0].title()+' is in the competitors.')
if 'theshy' in competitors:
print(competitors[1].title() + ' is in the competitors.')
#
competitors=["jacklove",'theshy','Feaker',"Rookie"]
if 'jacklove' in competitors:
print(competitors[0].title()+' is in the competitors.')
elif 'theshy' in competitors:
print(competitors[1].title() + ' is in the competitors.')
Jacklove is in the competitors.
Theshy is in the competitors.
#
Jacklove is in the competitors.
可以看到,代码不能正确运行。因为在 if-elif-… 中,有一个测试通过了,就会跳过余下的测试。
②. 使用if语句处理列表
注意缩进
competitors=["jacklove",'theshy','Feaker',"Rookie"]
for x in competitors:
if x=='theshy':
print(x+' is not in the team.')
else:
print(x+' is in the team.')
jacklove is in the team.
theshy is not in the team.
Feaker is in the team.
Rookie is in the team.
特别提醒: 在if语句中,如果列表名用在条件表达式中。只要列表不为空,其逻辑值均为True。
competitors=[]
if competitors:
for x in competitors:
print(x + ' is in the team.')
else:
print('No one is in the team.')
No one is in the team.
使用多个列表
competitors=["jacklove",'theshy','Feaker',"Rookie"]
competitors_01=["jacklove",'theshy','Leyan']
for x in competitors_01:
if x in competitors:
print(x+' is in the team.')
else:
print(x+' is not in the team.')
jacklove is in the team.
theshy is in the team.
Leyan is not in the team.
小细节:设置if语句的格式
if a<0:
if a < 0:
下面这句指令更方便阅读。