[英]If and elif in Python for good programming practices
Hello there I'm currently trying to get a good grasp of the if, elif, else structure in Python. 您好,我目前正在尝试很好地了解Python中的if,elif,else结构。 I'm trying some weird combinations in python having a test program to know the output in this if, if, elif, elif, else code. 我正在尝试在python中使用测试程序来了解一些奇怪的组合,以了解if,ifif,elif,else代码的输出。 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'
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. 如果我在put 1中将打印“ if2”,我想当我尝试更改“ intput == n”代码时,它也会打印“ elif2”和其他恶作剧。 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. 所以我的问题是我是否必须坚持if,elif,elif,.... n * elifs,在我看来似乎比使用古怪的if,if.if方法更有效的方法...,n * ifs,elif ,elif,... n * elif,否则。
Thanks 谢谢
The elif tree is designed such that at anywhere along if one of the statement turns out to be True
, the rest of the elif
s will not be evaluated. 该ELIF树设计使得在任何地方沿着如果语句的一个结果是True
,则其余elif
旨意不进行评估。
Here's a tutorial that might help you understand if else
better. 这里有一个教程 ,可以帮助你了解if else
更好的。
this may be more clear to understand: 这可能更容易理解:
if input == 0:
print "if1"
switch(input):
case 1:
print "if2"
break
case 0:
print "elif1"
break
case 1:
print "elif2"
break
default:
print "else"
break
of course, the code does not work. 当然,代码不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.