不使用全局变更另一个范围的变量?

时间:2017-09-06 09:54:00

标签: python

我是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)?

1 个答案:

答案 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