How can I share a variable between functions in Python?

前端 未结 5 793
一个人的身影
一个人的身影 2021-02-13 16:18

I have two functions, fun1 and fun2, which take as inputs a string and a number, respectively. They also both get the same variable, a, as

5条回答
  •  無奈伤痛
    2021-02-13 16:49

    An alternative to using classes: You can use the global keyword to use variables that lie outside the function.

    a = 5
    def func():
        global a
        return a+1
    
    print (func())
    

    This will print 6.

    But global variables should be avoided as much as possible.

提交回复
热议问题