How to change a variable after it is already defined?

前端 未结 6 1902
一整个雨季
一整个雨季 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:13

    # All the mumbo jumbo aside, here is an experiment 
    # to illustrate why this is something useful 
    # in the language of Python:
    a = 15    # This could be read-only, should check docs
    
    def test_1():
        b = a + 10    # It is perfectly ok to use 'a'
        print(b)
    
    def test_2():
        a = a + 10    # Refrain from attempting to change 'a'
        print(a)
    
    test_1()    # No error
    test_2()    # UnboundLocalError: ...
    

提交回复
热议问题