0

I have file2.py:

def add(b):
    global a
    return (a+b)

In file1.py:

a = 1
from file2 import *
print(add(3))

it gave me an error: NameError: global name 'a' is not defined

How can I get the number 4? Thanks in advance!

randominstanceOfLivingThing
  • 16,873
  • 13
  • 49
  • 72
Meng
  • 1,148
  • 5
  • 15
  • 23
  • 2
    The variable a is created in the global of file1.py You can pass the variable a directly to the add(a,b) and it should be easier. Or is it an exercise? – Marco smdm Nov 16 '16 at 14:56
  • 1
    Why dont define you function add(a, b): ?? – Wonka Nov 16 '16 at 14:57
  • 1
    See http://stackoverflow.com/questions/13034496/using-global-variables-between-files AND http://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable – Chris_Rands Nov 16 '16 at 14:58
  • I have a complex optimization objective function that takes only one input variable(like the function "add" in the post). now I want to add more variables to the function without changing the original objective function. – Meng Nov 16 '16 at 15:01
  • The original objective function as you said is already modified at the moment you are adding the "global a" you wrote above, isn't it? – Marco smdm Nov 16 '16 at 15:08
  • Hello Macro, sorry for the confusion. yes, i changed the objective function. I mean I don't want to change the optimization program as it only accepts objective function with a single input variable. – Meng Nov 16 '16 at 15:13
  • Thank you, Chris_Rands! these two posts are very helpful! – Meng Nov 16 '16 at 15:15
  • If you can make a small change I would use the first attached post of Chris and you will not have to screw up too much!! Hope this is enough to solve your query ;) Have a nice day. – Marco smdm Nov 16 '16 at 15:18

0 Answers0