How to access variables present in different functions?

2

What is the best way to access a variable that was created in a function? For example:

def Luggage():
    mala = []
    take = raw_input("O que você deseja levar na sua viagem?")
    mala.append(take)

If I wanted to access and use the mala list in another function, how should I proceed? In that case, would it be more interesting to use functions created within classes?

    
asked by anonymous 24.01.2016 / 14:58

2 answers

4

Everything you put inside a function is local to this function, you can not use it elsewhere. There are some solutions.

The first is to return the value - but not the variable - that you want, and then call the function can "capture" this value and do whatever you want.

Or you must create a variable somewhere else that can be used within the function. In this case there may be two alternatives. Some variable types may have their value passed to the function as argument and the function updates the received parameter, when the return function, the variable that had this value before the call will have the value placed inside the function.

The most common in these cases is to create a class that contains variables that are present in the class, then all functions within the class will have access to these class variables, so any change in it within one function will reflect all of the others.

For very simple examples, and only in these cases, you can declare the variable outside the function and it will be accessed by all functions. This is the equivalent of what you do with classes. But with classes you have a scope defined and do not cause confusion. In a very simple code that will not be used in a complex system, that is, in a script code, you can even use it without any confusion, but in other situations you should not use this form.

These two concepts of using variables outside the function are more advanced and I think that you should not try now that you have not yet mastered the basic function operation. For now just put a return:

def Luggage():
    mala = []
    take = raw_input("O que você deseja levar na sua viagem?")
    mala.append(take)
    return mala

Calling:

x = Luggage()
print(x)

See running on ideone .

    
24.01.2016 / 15:21
0

Suggestion is to use global variable definition:

def Luggage():
    global mala
    mala = []
    take = "O que voce deseja levar na sua viagem?"
    mala.append(take)
    take = "----teste------"
    mala.append(take)
    return mala

Luggage()

for i in mala:
    print (i)
    
06.02.2018 / 19:40