How to change a variable after it is already defined?

前端 未结 6 1903
一整个雨季
一整个雨季 2020-11-22 07:03

I\'m trying to add or subtract from a defined variable, but I can\'t figure out how to overwrite the old value with the new one.

a = 15

def test():
    a =          


        
6条回答
  •  甜味超标
    2020-11-22 07:17

    Scope of the variable is local to the block unless defined explicitly using keyword global. There is other way to access the global variable local to a function using globals function

    a = 15
    
    def test():
        a = globals()['a']
        a += 10
        print ( a )
    
    test()
    

    Above example will print 25 while keeping the global value intact i.e 15.

提交回复
热议问题