Well, it is because of the scope of variable each foo
is. The function foo()
is in the global scope, therefore can be called within other functions and outside of functions.
The variable foo
however, is in the local scope. That means it only "exists" inside of the function, it cannot be called or referenced outside of the function.
So, each different function creates its own local scope when it is called, and the variables created within are forgotten as soon as the scope is destroyed (the function ends).
Global variables can be accessed within local scope, local variables cannot be accessed in global scope.
If you want to create the variable in the global scope, call it like this:
global var
Here is an example of global and local scope:
var=1
def foo1():
var=3
foo1()
print(var) #prints 1 because the "var" in foo1() is locally assigned
def foo2():
global var
var=2
foo2()
print(var) #prints 2 because "var" is global
So, your function works because it i only assigning the name foo
locally, not globally.
However, if you call foo()
later in that function, it will raise an error because that local scope has assigned an int value to foo
, not a function, therefore is not callable.