Function - Global and local variables in Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I am learning Python. A book on Python 3 says the following code should work fine:

def funky():
    print(myvar)
    myvar = 20
    print(myvar)

myvar = 10
funky()

But when I run it in Python 3.3, I got the

UnboundLocalError: local variable  myvar  referenced before assignment

error. My understanding is that the first print(myvar) in funky should be 10 since it s a global variable. The second print(myvar) should be 20 since a local myvar is defined to be 20. What is going on here? Please help clarify.

Answers

You need to call global in your function before assigning a value.

def funky():
    global myvar
    print(myvar)
    myvar = 20
    print(myvar)

myvar = 10
funky()

Note that you can print the value without calling global because you can access global variables without using global, but attempting to assign a value will require it.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/14421733/global-and-local-variables-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils