Returning Variables in Functions Python Not Working Right

后端 未结 5 1743
庸人自扰
庸人自扰 2020-11-28 16:40

I have been trying to return a variable in a function in a variable and use it outside of it:

test = 0

def testing():
    test = 1
    return test

testing(         


        
5条回答
  •  感情败类
    2020-11-28 17:16

    Because you declare test in the function, it is not a global variable, thus, you can not access the variable test you created in the function outside of it as they are different scopes

    If you want to return test to a variable, you have to do

    result = testing()
    print(result)
    

    Or, you can also add a global statement:

    test = 0
    
    def testing():
        global test
        test = 1
        return test
    
    testing()
    print(test)
    

    By the way, when doing a conditional statement, you don't need the brackets around the 1==1 :).

提交回复
热议问题