Why does this code work:
var = 0
def func(num):
print num
var = 1
if num != 0:
func(num-1)
func(10)
but this one gives a “local variable ‘var’ referenced before assignment” error:
var = 0
def func(num):
print num
var = var
if num != 0:
func(num-1)
func(10)
Because in the first code, you have created a local variable
varand used its value, whereas in the 2nd code, you are using the local variablevar, without defining it.So, if you want to make your 2nd function work, you need to declare : –
in the function before using
var.Whereas in this code:
UPDATE: –
However, as per @Tim’s comment, you should not use a
globalvariable inside your functions. Rather deifine your variable before using it, to use it inlocal scope. Generally, you should try tolimitthe scope of your variables tolocal, and even inlocalnamespacelimitthe scope of local variables, because that way your code will be easier to understand.The more you increase the scope of your variables, the more are the chances of getting it used by the outside source, where it is not needed to be used.