Python Global Variables - Not Defined?

前端 未结 2 833
死守一世寂寞
死守一世寂寞 2021-01-20 20:39

I\'m running into an issue where a global variable isn\'t \"remembered\" after it\'s modified in 2 different functions. The variable df is supposed to be a data

2条回答
  •  深忆病人
    2021-01-20 21:03

    Yo have to use global df inside the function that needs to modify the global variable. Else (if writing to it) you are creating a local scoped variable of the same name inside the function and your changes wont be reflected to the global one.

    p = "bla"
    
    def func():
        print("print from func:", p)      # works, readonly access, prints global one
    
    def func1():
        try: 
            print("print from func:", p)  # error, python does not know you mean the global one
            p = 22                        # because function overrides global with local name   
        except UnboundLocalError as unb:
            print(unb)
    
    def func2():
        global p
        p = "blubb"                       # modifies the global p
    
    print(p)
    func()
    func1()
    print(p)
    func2()
    print(p)
    

    Output:

    bla   # global
    
    print from func: bla    # readonly global
    
    local variable 'p' referenced before assignment  # same named local var confusion
    
    bla    # global
    blubb  # changed global
    

提交回复
热议问题