【问题标题】:Passing a variable into a parameter defined by another function python将变量传递给另一个函数python定义的参数
【发布时间】:2019-05-13 20:22:51
【问题描述】:

我不确定为什么变量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

【问题讨论】:

    标签: python function parameter-passing


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 哎呀,我们俩同时编辑,我的编辑最终删掉了你的大部分帖子。您可能想edit 回复。我只是想删除第一句和最后一句。
      • 哦,好的。我想也许你的编辑在某些方面比我的好,所以我接受了。谢谢你的澄清。
      猜你喜欢
      • 2014-04-02
      • 1970-01-01
      • 2018-10-22
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多