嵌套全局变量/在嵌套函数中定义变量

Nested global variables / Defining a variable in a nested function

我在写程序的时候遇到了一个问题。我有一个 'counter' 计算计算机和玩家的胜利次数。问题是,我的函数嵌套在另一个函数中。如果没有 UnboundLocalError,我将如何完成此操作?我应该在哪里放置 global 语句或者我将如何完成它?

def nestedfunction():
    print("I am nested")
    score += 1
    print(score)
    again = input("would you like to play again? > ")
    if again == "yes":
         function()
else:
    exit()
def function():
    print("I am not nested")
    nestedfunction()
if __name__ == '__main__':
    score = 0
    function()

预期输出

I am not nested.
I am nested.
1
would you like to play again? > yes
I am not nested.
I am nested.
2

如果你想使用一个非本地变量,那么在它之前放一个全局变量来访问全局变量


    def nestedfunction():
        print("I am nested")
        global score 
        score += 1
        print(score)
        again = raw_input("would you like to play again?>")
        if str(again) == "yes":
            function()
        else:
            exit()

    def function():
        print("I am not nested")
        nestedfunction() 
    if __name__ == '__main__':
        score = 0
        function()

如果将分数作为参数发送而不是使用全局参数会更好