-3

i have 2 files

#foo.py
 global x
 def foo():
   x = 8


#main.py
from conf import *

 if __name__ == "__main__":
 foo()

how to get the X value in main.py file i have to use only 2 files here now if print or store x to other variable it has to print 8

  • `foo` is not assigning to a global `x`, since it does not define `x` to be global. The `x` within `foo` is local to `foo`. To make it global, it needs to be declared global inside the function, not outside of it. Move the global declaration to be inside of `foo`. – Tom Karzes Jun 03 '20 at 14:23
  • i have done but no change – jack sparrow Jun 03 '20 at 14:26
  • For starters, you have to put some form of `input foo` in `main.py`. Or is `conf` a typo for `foo`? – chepner Jun 03 '20 at 14:28
  • Well, that's only part of the problem. Try changing the import to `import foo`, then you can do `foo.foo()` and then examine `foo.x` and you should see it, provided it's global (which in the posted code it is not). – Tom Karzes Jun 03 '20 at 14:28
  • -@TomKarzes we can't do like that gives errors – jack sparrow Jun 03 '20 at 14:34
  • @Yashvanth It doesn't give errors. I'm assuming the file name is `foo.py`. I don't know what `conf.py` is. If you have `foo.py`, then `import foo` should work. If you can't get that much to work, then you have much more basic problems than accessing global variables. – Tom Karzes Jun 03 '20 at 15:07

2 Answers2

0

You can do something like this to get varaible x in main.py , if you declare x as global inside foo() that mean you will be accessing the global x not local x.

#foo.py
 x =10
def foo():
   x = 8
   print(" in foo x= " ,x)


#main.py
from conf import *
from foo import x, foo

if __name__ == "__main__":
   print(" x imported from foo.py  = ", x)
   foo()

OUTPUT

x imported from foo.py  =  10
in foo x=  8
Thomas Lazer
  • 178
  • 6
0

you have to use the global keyword properly

# foo.py
x = None

def foo():
    global x
    x = 8

#main.py
# this imports everything from foo in main
from foo import *

if __name__ == "__main__":
foo()
print(x)
omar
  • 190
  • 1
  • 10