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

时间:2016-01-16 01:39:20

标签: python-3.x nested global-variables global

我正在写一个程序,偶然发现了一个问题。我有一个'计数器'计算计算机和播放器的胜利数量。问题是,我的功能嵌套在另一个中。如果没有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

1 个答案:

答案 0 :(得分:0)

如果要使用非本地变量,请在其前面加上全局变量来访问全局变量


    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()

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

,那会更好