"if"和"else if"之间的主要区别是什么? [英] What's the main difference between 'if' and 'else if'?

查看:179
本文介绍了"if"和"else if"之间的主要区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

据一些专家称,

For e.g..

According to some experts,

这里的条件是互斥的:

if(n>0):
    print "Number is Positive"
if(n<0):
    print "Number is Negative"
if(n==0):
    print "Number is ZERO"

最好用elif和else重写

It would be better to rewrite with elif and else:

 if n > 0:
    print "Number is Positive"
 elif n < 0:
    print "Number is Negative"
 else:
    print "Number is ZERO"

所以我只想问一个问题:'if''elif'之间是否有区别?我知道'if'和'elif'之间的基本区别.但是我只想知道,为什么有些新手程序员更喜欢'elif'而不是'if'?

So I just want to ask the question that , Is there any difference between ' if ' and ' elif ' . I know the basic difference between ' if ' and ' elif '. But I just want to know , Why some novice programmers prefer ' elif ' over ' if '?

推荐答案

第一种形式if-if-if测试 all 条件,而第二种形式if-elif-else仅测试所需数量:如果找到True是一个条件,它将停止并且不评估其余条件.换句话说:当条件互斥时使用if-elif-else.

The first form if-if-if tests all conditions, whereas the second if-elif-else tests only as many as needed: if it finds one condition that is True, it stops and doesn't evaluate the rest. In other words: if-elif-else is used when the conditions are mutually exclusive.

让我们写一个例子.如果要确定三个数字之间的最大值,我们可以进行测试以查看一个值是否大于或等于另一个,直到找到最大值为止;但是一旦找到该值,就无需测试其他值:

Let's write an example. if you want to determine the greatest value between three numbers, we could test to see if one is greater or equal than the others until we find the maximum value - but once that value is found, there is no need to test the others:

greatest = None
if a >= b and a >= c:
    greatest = a
elif b >= a and b >= c:
    greatest = b
else:
    greatest = c
print greatest

或者,我们可以假定一个初始值最大,然后依次测试其他每个值以查看假设是否成立,并根据需要更新假设值:

Alternatively, we could assume one initial value to be the greatest, and test each of the other values in turn to see if the assumption holds true, updating the assumed value as needed:

greatest = None
if a > greatest:
    greatest = a
if b > greatest:
    greatest = b
if c > greatest:
    greatest = c
print greatest

如您所见,if-if-ifif-elif-else都是有用的,具体取决于您需要执行的操作.特别地,我的第二个示例更有用,因为将条件放入循环很容易-因此我们有多少个数字都没有关系,而在第一个示例中,我们需要写许多数字每增加一个数字,都需要手工进行.

As you can see, both if-if-if and if-elif-else are useful, depending on what you need to do. In particular, the second of my examples is more useful, because it'd be easy to put the conditional inside a loop - so it doesn't matter how many numbers we have, whereas in the first example we'd need to write many conditions by hand for each additional number.

这篇关于"if"和"else if"之间的主要区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆