How can I share a variable between functions in Python?

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

    Since a is defined outside the function scope and before the functions are defined, you do not need to feed it as an argument. You can simply use a.

    Python will first look whether the variable is defined in the function scope, and if not, it looks outside that scope.

    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)
    

    In this case you can also rewrite your functions into more elegant list comprehensions:

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

提交回复
热议问题