如果和elif在Python中进行良好的编程实践

Jan*_*pez 1 python if-statement

您好,我目前正在努力掌握Python中的if,elif,else结构.我在python中尝试了一些奇怪的组合,有一个测试程序来知道if if,if,elif,elif,else代码中的输出.但是我得到了这样奇怪的结果

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'
Run Code Online (Sandbox Code Playgroud)

如果我在1中它将打印"if2",我认为当我尝试更改"intput == n"代码时,它还会打印"elif2"和其他恶作剧.所以我的问题是我必须坚持使用if,elif,elif,.... n*elifs,否则我认为工作正常的方法比使用古怪如果,如果.... n*ifs,elif ,elif,... n*elifs,否则.

谢谢

Com*_*low 7

elif树的设计使得如果其中一个语句结果出现在任何地方,则不会评估s True的其余部分elif.

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