![](/img/trans.png)
[英]How would i make this program start over upon triggering the else statement?
[英]If statement not triggering
我试图使此代码在将i
设置为56和i
设置为0之间交替显示,但似乎无法触发第二个if语句。 第一个作品。
while True:
print 'is55 before if logic is' + str(is56)
if is56 == True:
i = 0
is56 = False
#print 'true statement' + str(i)
print 'True is56 statement boolean is ' + str(is56)
if is56 == False:
i = 56
is56 = True
print 'i is ' + str(i)
您有两个单独的if
,因此输入第一个,将is56
设置为False
,然后立即输入第二个并将其设置回True
。 相反,您可以使用else
子句:
while True:
print 'is55 before if logic is' + str(is56)
if is56:
i = 0
is56 = False
else: # Here!
i = 56
is56 = True
print 'i is ' + str(i)
有异议吗?
while True:
print 'is55 before if logic is' + str(is56)
i = is56 = 0 if is56 else 56
print 'i is ' + str(i)
第一个if
块中的更改将立即被下一个反向。
您想用单个if/else
块替换单独的if
块。
另外,您可以简单地使用itertools.cycle
对象来实现此目的:
from itertools import cycle
c = cycle([0, 56])
while True:
i = next(c)
print 'i is ' + str(i)
# some code
如果没有elif
,则原始代码(如果有效)将执行两个块。 为什么不:
def print_i(i):
print 'i is ' + str(i)
while True:
print_i(56)
print_i(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.