我不确定为什么变量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
在gettotalspeed()函数中,您忘记将totalspeed设置为全局变量,如
global totalspeed
。您可能还对return
的作用感到困惑。如果你想用“适当”的方式做,你可以做totalspeed = gettotalspeed(party_ids)
。希望这有帮助我怀疑你的问题在主程序中是不言而喻的:
在传递给函数的变量中,只定义了
NoOfEvents
party_ids
、totalspeed
和distance
没有定义学习Python作用域规则教程。最重要的是,请注意,函数定义了作用域块。当您离开函数时,函数内的变量被回收;他们的名字不适用于那个街区以外的地方。您发布的程序有三个独立的
totalspeed
变量相关问题 更多 >
编程相关推荐