Python global/local variables

后端 未结 6 1461
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 14:58

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 give

6条回答
  •  没有蜡笔的小新
    2020-12-01 15:47

    If you have var = ... anywhere in a function, the name "var" will be treated as a local variable for the entire function, regardless of where that assignment occurs. This means that all occurrences of var in your function will be resolved in the local scope, so the right hand side of var = var results in the referenced before assignment error because var has not yet been initialized in the function's scope.

提交回复
热议问题