• if if 和 if elif 的区别


    再一次编程中意外使用了if if 也实现了 if elif的功能,所以搜索了下其中的区别:

    1、if if 和 if elif 是有区别的,只是在某些情况下才会一样的效果;

    2、随意使用会导致意外的错误。

    现在举几个例子区别:

    程序一

    def analyzeAge( age ):
       if age < 21:
           print "You are a child"
       if age > 21:
           print "You are an adult"
       else:   #Handle all cases were 'age' is negative 
           print "The age must be a positive integer!"
    
    analyzeAge( 18 )  #Calling the function
    >You are a child
    >The age must be a positive integer!



    程序二
    def analyzeAge( age ):
       if age < 21:
           print "You are a child"
       elif age > 21:
           print "You are an adult"
       else:   #Handle all cases were 'age' is negative 
           print "The age must be a positive integer!"
    
    analyzeAge( 18 )  #Calling the function
    >You are a child

    上面的例子结果出错,表明 所有的if 后的命令都会运行,而elif后面的命令是根据上一个if是否运行,如果运行了,elif则略过,否则才运行

    另外时间也有区别,再举个例子:
    def multipleif(text):
        if text == 'sometext':
            print(text)
        if text == 'nottext':
            print("notanytext")
    
    def eliftest(text):
        if text == 'sometext':
            print(text)
        elif text == 'nottext':
            print("notanytext")
    
    text = "sometext"
    
    timeit multipleif(text)
    100000 loops, best of 3: 5.22 us per loop
    
    timeit elif(text)
    100000 loops, best of 3: 5.13 us per loop



  • 相关阅读:
    [Matlab] 短时傅里叶变换spectrogram函数
    [Word] Word中保存出矢量图
    [Matlab] Matlab 2020b Release Note
    [Matlab] Matlab 2020b Release Note
    [Matlab] Matlab 2020b Release Note
    [Matlab] Matlab 2020b Release Note
    [Matlab] 画图颜色扩展
    [脑电相关] 关于ERD现象
    [PPT技巧] PPT箭头设置及文字设置
    linux 新添加的硬盘格式化并挂载到目录下方法
  • 原文地址:https://www.cnblogs.com/zdwu/p/8072438.html
Copyright © 2020-2023  润新知