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并列更加合理。

总之:  =陈述语气,是设置值,也就是赋值,运算是从右到左侧

     ==疑问语气,是条件判断,判断是否相等,运算是从左到右侧

posted @ 2022-09-04 17:06  叕叒双又  阅读(498)  评论(0编辑  收藏  举报