Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I share a variable between functions in Python?

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 input. This is the code:

a = ['A','X','R','N','L']

def fun1(string,vect):
    out = []
    for letter in vect:
        out. append(string+letter)
    return out

def fun2(number,vect):
    out = []
    for letter in vect:
        out.append(str(number)+letter)
    return out

x = fun1('Hello ',a)
y = fun2(2,a)

The functions perform some nonsense operations. My goal would be to rewrite the code in such a way that the variable a is shared between the functions, so that they do not take it as input anymore.

One way to remove variable a as input would be by defining it within the functions themselves, but unfortunately that is not very elegant. What is a possible way to reach my goal?

The functions should operate in the same way, but the input arguments should only be the string and the number (fun1(string), fun2(number)).

like image 296
Federico Gentile Avatar asked Jan 13 '17 14:01

Federico Gentile


People also ask

How do you access a variable in a function from another file in Python?

You can't access the variables in functions, unless you return them or something.

How do you pass data between functions?

When there are multiple functions (which is most of the time), there needs to be a way to pass data between the functions. This is done by passing values in parenthesis: myFunction(myData). Even when there is no data to be passed, we still have to declare and execute functions by using parenthesis: myFunction().

How do you assign one variable to another in Python?

Python will joyfully accept a variable by that name, but it requires that any variable being used must already be assigned. The act of assignment to a variable allocates the name and space for the variable to contain a value. We saw that we can assign a variable a numeric value as well as a string (text) value.


2 Answers

Object-oriented programming helps here:

class MyClass(object):
    def __init__(self):
        self.a = ['A','X','R','N','L']  # Shared instance member :D

    def fun1(self, string):
        out = []
        for letter in self.a:
            out.append(string+letter)
        return out

    def fun2(self, number):
        out = []
        for letter in self.a:
            out.append(str(number)+letter)
        return out

a = MyClass()
x = a.fun1('Hello ')
y = a.fun2(2)
like image 140
ospahiu Avatar answered Oct 13 '22 19:10

ospahiu


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.

like image 43
involtus Avatar answered Oct 13 '22 19:10

involtus