Python Frequently Asked Questions, Release 3.9.5 9 2.2. Core Language Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring$_{global}$ for assigned variables provides a bar against unintended side-effects. On the other hand, if$_{global}$ was required for all global references, you’d be using$_{global}$ all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the$_{global}$ declaration for identifying side-effects. In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global. 2.2.2 What are the rules for local and global variables in Python? >>>def foo(): ... x =10 ... def bar(): ... nonlocal x ... print(x) ... x +=1 ... bar() ... print(x) >>> foo() 10 11 You can do a similar thing in a nested scope using the$_{nonlocal}$ keyword: >>> print(x) 11 This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope: In the example above you can access the outer scope variable by declaring it global: This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to $_{x}$, the compiler recognizes it as a local variable. Consequently when the earlier$_{print(x)}$ attempts to print the uninitialized local variable and an error results. >>> foo() Traceback (most recent call last): ... UnboundLocalError: local variable 'x' referenced before assignment >>> x =10 >>>def foobar(): ... global x ... print(x) ... x +=1 >>> foobar() 10