我是Python的新手。
我怎样才能完成这样的事情:
def gameon():
currentNum = 0
for x in range(100):
currentNum+=1
otherfunc()
def otherfunc(maybe a possible parameter...):
for y in range(500):
#check for some condition is true and if it is...
#currentNumFROMgameon+=1
我使用全局变量的实际代码:
def gameon():
global currentNum
currentNum = 0
for x in range(100):
currentNum+=1
otherfunc()
def otherfunc():
global currentNum
for y in range(500):
if(...):
currentNum+=1
global currentNum
如何在不currentNum
全球化的情况下完成此操作(从otherfunc
访问和更改currentNum
)?
答案 0 :(得分:1)
如果您想要访问currentNum
中的otherfunc
,则应将其传递给该功能。如果您希望otherfunc
更改它,只需让它返回更新版本即可。试试这段代码:
def gameon():
currentNum = 0
for x in range(100):
currentNum+=1
currentNum = otherfunc(currentNum)
def otherfunc(currentNumFROMgameon):
for y in range(500):
if True: # check your condition here, right now it's always true
currentNumFROMgameon+=1
return currentNumFROMgameon