Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python scope, dictionary and variables difference?

Python scope I have the same question but slightly different.

number = 0
def incrementNumber():
    number += 1

This one above does not work but this one below does why? Both are outside the function scope.

number = {'num':0}
def incrementNumber():
    number['num'] += 1

First one works if I add the variable as global

number = 0
def incrementNumber():
    global number
    number += 1
like image 931
Andreas Avatar asked Oct 07 '22 05:10

Andreas


1 Answers

Check out this blog post, it's similar to what you're doing. Specifically adam's comment.

You don't assign to dictionaryVar, you assign to dictionaryVar['A']. So it's never being assigned to, so it's implicitly global. If you were to actually assign to dictionaryVar, you'd get the behavior you were "expecting".

like image 193
John Avatar answered Oct 10 '22 02:10

John