[英]How can I stop a While loop?
我在 function 中写了一个while loop
,但不知道如何停止它。 当它不满足其最终条件时,循环永远只是 go。 我怎样才能阻止它?
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break #i want the loop to stop and return 0 if the
#period is bigger than 12
if period>12: #i wrote this line to stop it..but seems it
#doesnt work....help..
return 0
else:
return period
只需正确缩进代码:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
return period
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
return 0
else:
return period
您需要了解示例中的break
语句将退出您使用while True
创建的无限循环。 因此,当break条件为True时,程序将退出无限循环并继续下一个缩进块。 由于代码中没有后续块,因此函数结束并且不返回任何内容。 所以我通过用return
语句替换break
语句来修复你的代码。
按照你的想法使用无限循环,这是编写它的最佳方式:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
period = 0
break
return period
def determine_period(universe_array):
period=0
tmp=universe_array
while period<12:
tmp=apply_rules(tmp)#aplly_rules is a another function
if numpy.array_equal(tmp,universe_array) is True:
break
period+=1
return period
Python中的is
运算符可能不会按预期执行。 而不是这个:
if numpy.array_equal(tmp,universe_array) is True:
break
我会这样写:
if numpy.array_equal(tmp,universe_array):
break
将is
运营商的测试对象的身份,这是一件好事,从平等的完全不同。
我会使用for循环来完成它,如下所示:
def determine_period(universe_array):
tmp = universe_array
for period in xrange(1, 13):
tmp = apply_rules(tmp)
if numpy.array_equal(tmp, universe_array):
return period
return 0
这是 Charles Severance 的“python or everyone”中关于编写 while True 循环的一段示例代码:
while True:
line = input('> ')
if line == 'done':
break
print(line)
print('Done!')
这帮助我解决了我的问题!
from playsound import playsound
import time
ptr=1
while True:
try:
f= open("n.txt","r")
i=f.readline()
print(i)
if i!='ok':
i=int(i)
if i==1:
playsound('wm.mp3')
w=open('n.txt', 'w')
w.write()
i=f.readline()
print(f'sven{i}')
import hi
elif i==2:
playsound('pd.mp3')
w=open('n.txt', 'w')
if ptr ==1:
w.write()
ptr+=1
except:
print('')
在这段代码中,我想在一个条件下打开另一个 python 代码(hi),(hi)是一个 while true 循环,但我不会退出它并恢复主代码来检查其他条件。 我该怎么做???
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.