This is to do with Scope.
The place that variables are defined is important, and defining them in certain places will cause them to disappear elsewhere. Here is an example:
# PLEASE NOTE: This code will fail.
a = "Hello"
def my_func():
b = "Hello" # Declare a variable 'b', but only in this scope, in other words this function.
my_func()
print(a) # Works, since a is in the same scope.
print(b) # Fails, since b was defined inside a different scope, and discarded later.
Since, in your example, raiz
was declared inside the function funcion
, Python discarded it after funcion
was called. If you put the line:
raiz = 0
before your function definition, the function would simply update the variable, so there would be no issue, since the scope would be the same as where the print
statement occurs.
tl;dr: The variable raiz
was declared only in funcion
, so it was discarded afterwards.