将变量传递到由另一个函数定义的参数

2024-09-28 03:14:27 发布

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

我不确定为什么变量totalspeed变量没有正确地传递给函数startgame,因为startgame函数是在gettotalspeed函数之后调用的

从调用函数执行:

gettotalspeed(party_ids)
NoOfEvents=0
startgame(party_ids,totalspeed,distance,NoOfEvents)

功能

def gettotalspeed(party_ids):
    #Get selected party members IDS
    print(party_ids)
    #Obtain Speeds
    ids_string = ','.join(str(id) for id in party_ids)
    mycursor.execute("SELECT startspeed FROM characters WHERE CharID IN ({0})".format(ids_string))
    myspeeds=mycursor.fetchall()
    totalspeed=0
    for speedval in myspeeds:
        totalspeed=totalspeed + speedval[0]
    print("totalspeed is: ",totalspeed)
    return totalspeed
def startgame(party_ids,totalspeed,distance,NoOfEvents):
    #Check if game end
    print(totalspeed)
    while distance!=0:
        #Travel...
        distance=distance-totalspeed
        NoOfEvents=NoOfEvents+1
        #Generate Random Encounter
        genevent(NoOfEvents)
    return NoOfEvents

产生的错误:

NameError: name 'totalspeed' is not defined

输出(ignoring party_ids

totalspeed is:  15

Tags: 函数inididsforstringisparty
2条回答

在gettotalspeed()函数中,您忘记将totalspeed设置为全局变量,如global totalspeed。您可能还对return的作用感到困惑。如果你想用“适当”的方式做,你可以做totalspeed = gettotalspeed(party_ids)。希望这有帮助

我怀疑你的问题在主程序中是不言而喻的:

gettotalspeed(party_ids)
NoOfEvents=0
startgame(party_ids,totalspeed,distance,NoOfEvents)

在传递给函数的变量中,只定义了NoOfEventsparty_idstotalspeeddistance没有定义

学习Python作用域规则教程。最重要的是,请注意,函数定义了作用域块。当您离开函数时,函数内的变量被回收;他们的名字不适用于那个街区以外的地方。您发布的程序有三个独立的totalspeed变量

相关问题 更多 >

    热门问题