By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,481 Members | 3,170 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,481 IT Pros & Developers. It's quick & easy.

How Can I share common variable between two functions?

P: 3
Can func1 share variable a with func2 without global keyword in python?

def func1():
a= 5
print(a)

def func2():
print(a)

func1()
func2()
Apr 26 '19 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 621
For the code posted above, the variable, a, is local to/only exists in func1. You have to return it for it to exist outside the function. Every tutorial covers this. Tutorials are write once, read many, so we don't have to answer the same questions over and over and over. Start with this part of a the tutorials point tutorial http://www.tutorialspoint.com/python..._functions.htm
Apr 26 '19 #2

P: 7
You can define both functions in a class, and make a as an attribute.

class A:
def __init__(self, a):
self.a = a
def func1(self):
self.a= 5
print(self.a)
def func2(self):
print(self.a)
obj = A(4)
obj.func2()
obj.func1()


The output will be.

4
5
Apr 27 '19 #3

Post your reply

Sign in to post your reply or Sign up for a free account.