[英]Calling a function to obtain a new value for each iteration of a loop in Python
I have written a function, getSteps()
which uses the random package, which should return a different value each time (it does when I run the function multiple times manually). 我编写了一个函数
getSteps()
,该函数使用随机包,该函数每次都应返回一个不同的值(当我多次手动运行该函数时会返回一个不同的值)。
But when I call it inside a for loop or while loop, the script just calls the function once and then uses the value returned for the first iteration for each iteration thereafter. 但是,当我在for循环或while循环中调用它时,脚本只调用一次函数,然后将第一次迭代返回的值用于此后的每次迭代。
I am attempting to call the function as follows: 我试图按以下方式调用该函数:
F = open("outFile.txt","w")
for i in range(6,100): ## for each of these values
for j in range(0,100): ## call the function 100 times
steps = getSteps(i)
F.write(str(i)+","+str(steps)+"\n")
It should have a different value for each iteration, but I find each is the same. 对于每次迭代,它应该具有不同的值,但是我发现每一个都是相同的。 Could anyone tell me how to fix this?
谁能告诉我该如何解决?
The function is defined as below: 该函数定义如下:
def getSteps(maxSteps):
global numberSteps, numberAttempts, found
while (found == False):
sourceJar = psj[random.randrange(0, len(psj))]
if sourceJar in pdj:
pdj.remove(sourceJar)
destJar = pdj[random.randrange(0, len(pdj))]
if sourceJar == 8 and destJar == 5:
etf()
elif sourceJar == 8 and destJar == 3:
ett()
elif sourceJar == 5 and destJar == 8:
fte()
elif sourceJar == 5 and destJar == 3:
ftt()
elif sourceJar == 3 and destJar == 8:
tte()
elif sourceJar == 3 and destJar == 5:
ttf()
found = checkFound()
outString = "Pour the " + str(sourceJar) + " litre jar into the " + str(
destJar) + " litre jar. The volumes for each jar are now "
outString += "8-" + str(jar8volume) + ",5-" + str(jar5volume) + ",3-" + str(jar3volume)
##print outString
updateLists()
if (numberSteps >= maxSteps):
numberAttempts += 1
reset()
##print "Currently on iteration number " + str(numberAttempts)
numberSteps += 1
return numberAttempts + 1
There's a lot of code you're not showing. 您没有显示很多代码。 But presumably the problem is that you use global variables inside
getSteps
; 但是大概的问题是您在
getSteps
使用了全局变量; once found
is set to True on the first invocation, it will remain true and none of the code inside the if
block will execute on subsequent calls. 一旦
found
则在第一次调用时将其设置为True,它将保持为true,并且if
块中的任何代码都不会在后续调用中执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.