Search code examples
pythonfunctionimportreturn

In Python I have two different files


In a Python code, I am trying to access a variable from a function in another file. The codes are:

File1.py:

S1 = [a,b,c,d,e]
S2 = [a,b,d,e]
def fc1(S1,S2):
    ...
    diag = S1 + S2
    return(diag)

File2.py:

from File1 import fc1,fc2
S1 = [a,b,c,d]
S2 = [a,b,d]
...
fc1(S1,S2)
print(diag)
...

However, it gives an error message:

Traceback (most recent call last):
  File "C:\...\File.py", line 102, in <module>
    print(diag):
NameError: name 'diag' is not defined

How can I access the diag variable from File2.py? I tried to assign as a global but it doesn't work. Any help will be greatly appreciated.


Solution

  • You must first define 'diag' variable in File2.py:

    diag = fc1(S1,S2)
    

    and then print it:

    print(diag)