python 3.x - Nested global variables / Defining a variable in a nested function -


i writing program , stumbled across problem. have 'counter' counting how many wins computer , player. problem is, function nested in another. how accomplish without unboundlocalerror? put global statement or how accomplish it?

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

expected output:

i not nested. nested. 1 play again? > yes not nested. nested. 2 

if want use variable not local put global before access global variable

      def nestedfunction():         print("i nested")         global score          score += 1         print(score)         again = raw_input("would play again?>")         if str(again) == "yes":             function()         else:             exit()      def function():         print("i not nested")         nestedfunction()      if __name__ == '__main__':         score = 0         function()  

it better if sent score parameter rather using global


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -