is it possible to create a local variable inside a function and import it into another python file. And if it is it possible please write a code snippet in the comments. Thank you very much.
CodePudding user response:
You can simply use file2.var
. A sample code would be:
file1.py
import file2
print(file2.x)
file1.func()
print(file2.x)
file2.py
x = 5
def func():
global x
x = 7
Output when you run file1.py
5
7
CodePudding user response:
global variable are declared in global scope.
variable declared inside function are local variable.
also, you can't access local variable outside its scope.
v1 = "global variable" # global variable
def function():
v2 = "local variable" # local variable
print(v1) # OK
print(v2) # NameError: name 'v2' is not defined