0

I am calling script2 from script1 and would like to use the variable determined from script2 in script 1.

script1

a = 1
import script2
script2.dosomething(a)
print b

script2

def dosomething(a):
    b = a+2

B is not recognized in script 1. Is there any way around this?

TYL
  • 1,577
  • 20
  • 33

3 Answers3

3

in script1:

a = 1
import script2
b = script2.dosomething(a)
print(b)

in script 2:

def dosomething(a):
    return a+2

I think the mistake is dosomething does not return anything, and the variable b in the function is a local variable.

Ray
  • 176
  • 1
  • 8
1

What you're looking for is a "return" statement. You can tell the function to send back the variable to the other piece of code that called the function.

Here is a good resource to learn about functions and how they return: https://www.pitt.edu/~naraehan/python2/user_defined_functions.html

In practice, your code would end up similar to this:

script2.py

def dosomething(a):
    return a + 2

script1.py

import script2.py
a = 1
result = script2.dosomething(a)
print result
0

When you call a script, the calling script should access the namespace of the called script. (In your case, first can access the namespace of second.) However, what you are asking for is the other way around. Your variable is defined in the calling script, and you want the called script to access the caller's namespace. Check here : Stackoverflow answer

Mayank Srivastava
  • 149
  • 1
  • 3
  • 18
  • Please don't post answers which are just pointers to other answers. Once you have sufficient reputation, you can nominate to close as duplicate. – tripleee Feb 16 '18 at 06:05