将变量传递给另一个函数python定义的参数

时间:2019-05-13 20:22:52

标签: python function parameter-passing

我不确定为什么变量key:value不能正确地传递给函数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

2 个答案:

答案 0 :(得分:0)

您忘记在gettotalspeed()函数中使totalspeed成为global totalspeed这样的全局变量。您可能会对return的功能感到困惑。如果您想以“适当”的方式进行操作,则可以进行totalspeed = gettotalspeed(party_ids)。希望这会有所帮助!

答案 1 :(得分:0)

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

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

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

阅读有关Python作用域规则的教程。最重要的是,请注意,函数定义了作用域块。离开函数时,将回收函数内部的变量;它们的名称不适用于该区域。您发布的程序具有三个独立的totalspeed变量。

相关问题