Global variable used in multiple functions

Asked

Viewed 2,796 times

2

I have this code:

donos=[]
def calcula_media():

    lista_dicionario= [1,2,3]
    donos.extend(lista_dicionario)

def funcao2():

    print donos

How can I use the global variable in the 2nd function using what I used in the 1st to do the extend, that is to obtain [1,2,3] in the 2nd function?

  • Is there a problem? The best answer I can give you is not to do this. Avoid global.

  • Yes, I have a function ( a 1º ) that allows to obtain a list of dictionary, that I have already obtained and the 2nd that transforms this list of dictionary obtained in a CSV file , that I also know how to do , I just do not know how to get the list of the 1st function for the 2nd

  • I don’t see any problem, you’re doing what you say you want.

  • No , in the 2nd function owners is an empty variable do not know why

  • http://ideone.com/z5rSkv

  • what lines 9 and 10 do ?

  • Call the functions, no calling, no executing

  • That’s right already gave , thanks :)

Show 3 more comments

1 answer

3


From what I understand only needed to call the functions:

donos = []
def calcula_media():
    lista_dicionario = [1,2,3]
    donos.extend(lista_dicionario)

def funcao2():
    print(donos)

calcula_media()
funcao2()

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Ideally in real code in complex application, the best thing to do is not to use global variables like this and always pass as argument.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.