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

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

问题描述

例如...

一些专家认为,

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测试所有条件,而第二种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.

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

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