How can I share a variable between functions in Python?

前端 未结 5 780
一个人的身影
一个人的身影 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:48

    This can be easily achieved using the global keyword. That makes the a variable available in the whole file. However, the global variables should be avoided as much, because every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.

    a = ['A','X','R','N','L']
    
    def fun1(string):
        out = []
        for letter in a:
            out. append(string+letter)
        return out
    
    def fun2(number):
        out = []
        for letter in a:
            out.append(str(number)+letter)
        return out
    
    x = fun1('Hello ')
    y = fun2(2,a)
    

提交回复
热议问题