调用函数为Python中循环的每次迭代获取新值

2024-10-02 16:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一个函数getSteps(),它使用随机包,每次都应该返回一个不同的值(当我手动多次运行该函数时会返回)

但是当我在for循环或while循环中调用它时,脚本只调用函数一次,然后在以后的每次迭代中使用第一次迭代返回的值

我试图按如下方式调用函数:

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")

每个迭代应该有不同的值,但我发现每个都是一样的。有人能告诉我怎么修吗

功能定义如下:

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

Tags: andtheinforifeliffoundstr
1条回答
网友
1楼 · 发布于 2024-10-02 16:34:27

有很多代码你没有显示。但问题大概是在getSteps中使用全局变量;一旦found在第一次调用时设置为True,它将保持True,并且if块中的任何代码都不会在随后的调用中执行

相关问题 更多 >