本文介绍了Python中的if和elif以获得良好的编程习惯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我目前正在尝试很好地了解Python中的if,elif和else结构.我正在尝试一些具有测试程序的python怪异组合,以了解if,ifif,elif,else代码的输出.但是我得到了这样奇怪的结果

Hello there I'm currently trying to get a good grasp of the if, elif, else structure in Python. I'm trying some weird combinations in python having a test program to know the output in this if, if, elif, elif, else code. However I'm getting weird results such as this

input = raw_input('Please enter the required digit: ')
intput = int(input)

if intput == 0:
    print 'if1'

if intput == 1:
    print 'if2'
elif intput == 0:
    print 'elif1'
elif intput == 1:
    print 'elif2'
else:
    print 'else'

如果我在put 1中将打印"if2",我想当我尝试更改"intput == n"代码时,它也会打印"elif2"和其他恶作剧.所以我的问题是我是否必须坚持if,elif,elif,.... n * elifs,else方法在我看来似乎比使用古怪的if,if ... ,elif,... n *个elif,否则.

if I in put 1 it will print "if2", I thought that it will also print "elif2" and other shenanigans when I try to change the "intput == n" code. So my question is do I have to stick to the if,elif, elif, .... n * elifs, else method which seems to me working alright than working with the wacky if,if.... n * ifs, elif, elif, ...n* elifs, else.

谢谢

推荐答案

elif树的设计使得在语句中的任何一个结果为True的任何地方,其余elif都不会被评估.

The elif tree is designed such that at anywhere along if one of the statement turns out to be True, the rest of the elifs will not be evaluated.

这是一个教程,可以帮助您更好地理解if else.

Here's a tutorial that might help you understand if else better.

这篇关于Python中的if和elif以获得良好的编程习惯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 21:37