Global variables referencing in python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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.

Answers

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

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

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/35706903/global-variables-referencing-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils