+ 1
Defining Variables in Functions
So, I was having trouble making a function define a variable within it. This is an example: def TESTA(): Answ=2 I would set Answ=1 before testing TESTA(), but whenever I ran TESTA() then checked Answ, Answ=1. Any help?
2 Réponses
+ 1
Lo correcto seria:
def TESTA():
return 2
....
Answ=TESTA()
Defines TESTA() para que devuelva el valor que tu quieres y en el código principal asignas la función TESTA() a una variable para asignarle el valor que devuelve la función.
0
There is this thing called Variable Scope which basically means that - in order to prevent functions from overriding other variables or loops from breaking - some variables live in their own separate environments.
This means that variable called spam that you declare I'm your program is not the same variable called spam that you called from a function.
This means that the lifespan of variables called in functions and loops is as long as the lifespan of the function or the loop iteration. This is why you never clear variables at the end of a function and you always keep variables outside of a loop if you need them to persist.
long story short, even though to you it seems like the same variable, these are two different variables sharing a name but pointing to two different values in computer's memory.