在不使用全局变量的情况下从另一个范围更改变量?

2024-06-02 07:56:06 发布

您现在位置: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


Tags: inforifparameterisdefcheckrange
1条回答
网友
1楼 · 发布于 2024-06-02 07:56:06

如果您想访问otherfunc中的currentNum,应该将其传递给该函数。如果您想要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

相关问题 更多 >