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

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

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

  • 相关阅读:
    Selenium2+python自动化17-JS处理滚动条
    图论一
    HDU1106
    银行家算法学习笔记
    NYOJ 540
    我在博客园 2013-08-02 22:04 200人阅读 评论(0) 收藏
    编程之美:平面最近点对
    RIA算法解决最小覆盖圆问题
    求两直线交点和三角形内外心
    求圆心
  • 原文地址:https://www.cnblogs.com/guochaoxxl/p/16655460.html
Copyright © 2020-2023  润新知