-2

I want to share variables between two functions: from the bottom one to the top one

def number_function():
   print(number_1)
   print(number_2)

number_function()

def test():
   number_1=10
   number_2=20

When I have tried to run the code I get this error

NameError: name 'number1' is not defined
Mark
  • 90,562
  • 7
  • 108
  • 148
  • Variables are scoped to functions. If you want to access those variables, `test()` should return them. – Mark Jul 24 '19 at 23:21
  • Possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Jin Lee Jul 25 '19 at 02:31

2 Answers2

0

As pointed out by Mark Meyer, the variables are scoped to functions and there is no way for variables inside test to exist if you do not call the function test() function.

In case you do run test() and don't want to return and pass variables to other functions, you would need to define the variables as global, so they are not confined to the function scope.

def test():
    global number_1
    global number_2
    number_1=10
    number_2=20

def number_function():
    print(number_1)
    print(number_2)

test()
number_function()

Out[1]:
10
20

Another way to share variables across functions is to simply use classes:

Class yourEnv(object):

    def __init__(self):
         self.number_1 = 10
         self.number_2 = 20

    def number_function(self):
        print(self.number_1)
        print(self.number_2)

yourEnv().number_function()

Out[2]
10
20
realr
  • 3,652
  • 6
  • 23
  • 34
0

can id do the reverse ?, for example :

def test():
    print(number_1)
    print(number_2)        

def number_function():

    global number_1
    global number_2
    number_1=10
    number_2=20
test()
number_function()