2017-09-06 49 views
0

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

我怎样才能做到这一点(访问和来自otherfunc改变currentNum)未做currentNum全球?

+0

您是否曾尝试将'currentNum'传递给该函数并让该函数返回'currentNum'的修改版本? – araknoid

+0

@araknoid啊,工作,谢谢。但是,如果它应该通过一个基于某些条件返回true或false的函数,但它也必须增加“currentNum”? –

回答

1

如果你想访问currentNumotherfunc你应该把它传递给该函数。如果你想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 
+0

谢谢!但是,如果它应该通过一个基于某些条件返回true或false的函数,但它也必须增加“currentNum”? –

+0

@overso您可以编写一个单独的函数,返回True或False。该函数将不得不接收它需要的任何输入变量。虽然通常如果这样的检查足够简单,只要在if语句中检查它就容易了,而不是为它编写单独的函数。 – Swier