Python if vs. else if vs. else语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19946963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:03:02  来源:igfitidea点击:

If vs. else if vs. else statements?

pythonif-statement

提问by Eed

Are:

是:

if statement:
if statement:

the same as

一样

if statement:
elif statment:

and

if statement:
else statement:

the same? If not, what's the difference?

相同?如果不是,有什么区别?

采纳答案by Christian Stewart

No, they are not the same.

不,它们不一样。

if statement:
if statement: 

If the first statement is true, its code will execute. Also, if the second statement is true, its code will execute.

如果第一条语句为真,则执行其代码。此外,如果第二个语句为真,则将执行其代码。

if statement:
elif statment:

The second block will only execute here if the first one did not, and the second check is true.

如果第一个块没有执行,第二个块才会在这里执行,并且第二个检查为真。

if statement:
else:

The first statement will execute if it is true, while the second will execute if the first is false.

如果第一个语句为真,则执行第二个语句,如果第一个语句为假,则执行第二个语句。

回答by Paul Draper

The first one is different

第一个不一样

if True:
    print 'high' #printed
if True:
    print 'low'  #printed

than the second

比第二个

if True:
   print 'high' #printed
elif True:
   print 'low'  #not printed

and the third is invalid syntax

第三个是无效的语法

See tutorial.

教程

回答by Krish R

if statement:

if statement:

It is like individual conditions; each ifstatement is checked one after another.

这就像个人条件;每个if语句都被一个接一个地检查。

The same as:

等同于:

if statement:

elif statment:

It is like: the first ifcondition failed then check the next after the condition.

就像:第一个if条件失败然后在条件之后检查下一个。

And:

和:

if statement:

如果语句:

else statement:

其他语句:

It is like: Check the first ifcondition, and then execute the elseblock.

就像:检查第一个if条件,然后执行else块。