python中的if和elif区别
代码1:
1 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] 2 for number in numbers: 3 if number == 1: 4 res='st' 5 if number == 2: 6 res='nd' 7 if number == 3: 8 res='rd' 9 else: 10 res='th' 11 print(f"{number}{res}")
结果:
python code1.py
1th
2th
3rd
4th
5th
6th
7th
8th
9th
代码2:
1 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] 2 for number in numbers: 3 if number == 1: 4 res='st' 5 elif number == 2: 6 res='nd' 7 elif number == 3: 8 res='rd' 9 else: 10 res='th' 11 print(f"{number}{res}")
结果:
python code1.py
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
由此可见,code1中使用if时,只有number==3时,才发生改变,1和2时被3给覆盖了。code2中,使用elif时,三种情况1 2 3时全部进行处理,根据实际情况,只需要其中一种使用if并列即可。如果也许需要多种情况均满足,使用elif并列更加合理。
总之: =陈述语气,是设置值,也就是赋值,运算是从右到左侧
==疑问语气,是条件判断,判断是否相等,运算是从左到右侧
人就像是被蒙着眼推磨的驴子,生活就像一条鞭子;当鞭子抽到你背上时,你就只能一直往前走,虽然连你也不知道要走到什么时候为止,便一直这么坚持着。