Search code examples
pythonc++global-variablesglobal

Why python need global keyword while C/C++ no need?


If I want change a global variable, I could do it directly in C++:

#include <stdio.h>

int x = 1;

int main()
{
    x = 1 + x;
    printf("%d\n", x);
    return 0;
}

But got error using Python:

x = 1
def foo():
    x += 1

foo()

UnboundLocalError: local variable 'x' referenced before assignment

I have to add global x in function foo to make it.


Seems python make it more explicit, is "just to be explicit" the reason?


Solution

  • The fundamental difference is that C and C++ have variable declarations. The location of the declaration determines whether a global is declared.

    In Python, you only have assignments. An assignment to a yet-unassigned variable creates that variable. An assignment to an existing variable changes that variable. Hence, without global you couldn't create a local variable if a global variable with that name existed.