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)
).
You can't access the variables in functions, unless you return them or something.
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().
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With