1

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.

1
  • you're mixing globals and locals. When you pass a variable to a function that variable is a local variable. Remove the function arguments and add global val, val2 to the beginning of all the functions. Commented Feb 29, 2016 at 18:36

2 Answers 2

1

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

val, val2 = func()
val, val2 = func1(val, val2)
func2(val, val2)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.