Python global/local variables

后端 未结 6 1458
没有蜡笔的小新
没有蜡笔的小新 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:31

    In your second piece of code you have created a local variable in RHS and without defining it, you are assigning it to the LHS variable var which is global (a variable defined outside the function is considered global explicitly).

    If your intention is to create a local variable inside the function and assign it to the value of the global variable, this will do the trick:

    var = 0
    
    def func(num):
        print num
        func.var = var # func.var is referring the local
                       # variable var inside the function func
        if num != 0:
            func(num-1)
    
    func(10)
    

提交回复
热议问题