本文介绍了Python:elif还是新的if?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最好使用:
if var in X:
#do_whatever
elif (var in Y):
#do_whatever2
或:
if var in X:
#do_whatever
if var in Y:
#do_whatever2
假设var不能同时出现在X和Y中......是否有任何规则或常规做法?我应该使用elif吗?还是一个新的if?或者没关系??
Assuming var can't be in both X and Y... Is there any rule or common practice? Should I use elif? or a new if? or it doesn't matter??
编辑:很棒的答案..但是,如果第一个语句(#do_whatever)以返回或中断结束,我可以这么说吗?在最后,其他条件将不会被测试因此浪费系统资源或造成麻烦,可以做任何事情......我猜...
Great answers.. But can I say that if the first statement (#do_whatever) ends with a return or a break; where in its end the other condition will not be tested thus wasting the system resources or causing trouble, it's ok to do whatever.. I guess...
推荐答案
在某些情况下会有所不同。
参见此示例:
It makes a difference in some cases.See this example:
def foo(var):
if var == 5:
var = 6
elif var == 6:
var = 8
else:
var = 10
return var
def bar(var):
if var == 5:
var = 6
if var == 6:
var = 8
if var not in (5, 6):
var = 10
return var
print foo(5) # 6
print bar(5) # 10
这篇关于Python:elif还是新的if?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!