-3

This is a simplified example of my problem. I need to use a variable which I have created in another function, but putting global before the variable instantiation doesn't work.

x = 10
def one():
    global x
    a = x +2
    b = a/2
    print (b)
def two():            
    one()             
    c = int(input())            
def three():
    global a
    global c           
    d = c + a         
    print(b)

two()         
three()
Rafael
  • 7,002
  • 5
  • 43
  • 52
guverner2
  • 1
  • 1

3 Answers3

2

To use a global variables in Python you need to declare them as such:

x = 10

def one():
    global x
    global a
    global b
    a = x +2
    b = a/2
    print (b)

def two():            
    one()             
    global c
    c = int(input())            

def three():
    global a
    global c           
    d = c + a         
    print(d)
    print(b)

two()       
three()

In Python, a variable defined on top of the file (not within a function, an if statement etc) is considered as a global variable and is accessible throughout the file (in other functions etc) but also to any file importing that file.

A variable defined in a scope other than the main body (say a function) it's accessible to that function only. In this case, if you define a new variable within a body other than the main body, you need to tell Python that this variable is global just before you create the variable. Similarly, if you need to access a global variable, you need to use global var just before you try to access it.

Not the best implementation. I will recommend, as others already did, to use a class or functions with arguments and returns instead.

Rafael
  • 7,002
  • 5
  • 43
  • 52
0

Use the return statement and function parameters:

x = 10
def one(x):
    a = x +2
    b = a/2
    print(b)
    return a, b

def two():                        
    c = int(input()) 
    return c    

def three(a, b, c)                 :         
    d = c + a         
    print(b)

a, b = one(x)
c = two()         
three(a, b, c)
Netwave
  • 40,134
  • 6
  • 50
  • 93
-1

You could try to move these three functions into some class, create an 'x' attribute in this class, and then use this 'x' in the functions above as self.x