首页 > 解决方案 > 将变量传递给另一个函数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

标签: pythonfunctionparameter-passing

解决方案


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

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

在您传递给函数的变量中,只有NoOfEvents被定义。 party_ids, totalspeed, 并且distance没有定义。

完成有关 Python 范围规则的教程。最重要的是,请注意一个函数定义了一个作用域块。离开函数时,函数内部的变量会被回收;他们的名字不适用于该块之外。您发布的程序具有三个独立totalspeed变量。


推荐阅读