user42836
user42836

Reputation: 193

Global variables referencing in python

I am trying to write a program with python functions. The variables used in one function will be needed in various other functions.

I have declared it as global in the first function, then used the returned value in the second function. However in the third function, I would like to use the updated value from the second, but I am only able to get the values from the first function.

def func():
    global val, val2
    val = 3
    val2 = 4
    return val, val2

def func1(val, val2):
    val = val + 1 
    val2 = val2 + 1
    return val, val2

def func2(val,val2):
    val = val + 1
    val2 = val2 + 1
    print val, val2

func()
func1(val, val2)
func2(val, val2)

I would like to get 5,6 as the answer, but am getting 4,5.

Upvotes: 1

Views: 84

Answers (2)

Tony Babarino
Tony Babarino

Reputation: 3405

If the variable is declared as a function argument, it's a local variable for this function. In Your case if You declare def func1(val,val2): then val,val2 will both be local in function func1. If You want to use global variables do it like that:

def func():
    global val,val2
    val=3
    val2=4
    return val,val2
def func1():
    global val,val2
    val=val+1
    val2=val2+1
    return val,val2
def func2():
    global val,val2
    val=val+1
    val2=val2+1
    print val,val2
func()
func1()
func2()

returns:

5 6

But I think that using global variables should be avoided if using them is not necessary (check Why are global variables evil?). Consider using return the right way like in pp_'s answer.

Upvotes: 1

pp_
pp_

Reputation: 3489

Assign the return values of your functions to val and val2.

val, val2 = func()
val, val2 = func1(val, val2)
func2(val, val2)

Upvotes: 1

Related Questions