python - 将变量传递给另一个函数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
解决方案
我怀疑您的问题在主程序中是不言而喻的:
gettotalspeed(party_ids)
NoOfEvents=0
startgame(party_ids,totalspeed,distance,NoOfEvents)
在您传递给函数的变量中,只有NoOfEvents
被定义。 party_ids
, totalspeed
, 并且distance
没有定义。
完成有关 Python 范围规则的教程。最重要的是,请注意一个函数定义了一个作用域块。离开函数时,函数内部的变量会被回收;他们的名字不适用于该块之外。您发布的程序具有三个独立totalspeed
变量。
推荐阅读
- python - How to append aggregated chunks to list using Python/Pandas?
- visual-studio-code - 如何纠正 Visual Studio Code 中的键定义?
- pine-script - 将 Pine Script Trailing Stop 转换为 version4
- c# - 如何使用 libphonenumber 查找电话号码?
- swiftui - 使用 SwiftUI。我的滑块/侧边菜单在单击时会启动新视图,但单击
按钮,现在所有选项都“死”了 - formal-verification - 在 Dafny 的 Ensure 子句中调用另一个引理
- javascript - 如何在 Puppeteer 中实现 page.type()?
- html - 如何避免过渡和变换结合时对“悬停”的“抖动效应”?
- python - 如何将数据框列对转换为单个字典映射?
- html - 将 div 固定到页面中心,但调整大小时不会溢出