再一次编程中意外使用了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