Aladine Aladine - 3 months ago 5
Python Question

Passing data mid-function back to function Python

The below script works fine, until I added in "def test", I am trying to get rid of all global variables my programming in general and as I'm not a great programmer, I hope there is a way to do this.

I want to pass "foo" from function "test" back to Function "work" but this does not work as its not a global variable. Any ideas?

bar = "bar"
barnone = "barnone"

def function_A():
data = 5
data1 = 15
if host == 1:
work(data, data1)
else:
function_B()

def function_B():
data = 3
data1 = 13
work(data, data1)
test(data)
print foo

def work(data,data1):
print data
print data1
test(data)
print foo

def test(data):
if data == 3:foo = bar
elif data == 5:foo = barnone

if __name__ == '__main__':
host = 11
function_A()


EDIT:

Thank you, this works... I appreciate all the feedback as I am a novice, keep in mind this was just a test script I put together to understand passing parameters to different functions. Before this I was using globals and I'm trying to get rid of them.

Thank you, any advice is helpful.

bar = "bar"
barnone = "barnone"

def function_A():
data = 5
data1 = 15
if host == 1:
work(data, data1)
else:
function_B()

def function_B():
data = 3
data1 = 13
work(data, data1)
test(data)

def work(data,data1):
print data
print data1
test(data)
print test(data)

def test(data):
if data == 3:foo = bar
elif data == 5:foo = barnone
return foo

if __name__ == '__main__':
host = 11
function_A()

Answer

Add the following to the end of your test() function:

`return foo`

then you can print the variable in work() like this

print test(data)