I'm reading from Miller and Ranum's book on Algorithms and Data Structures using Python. They use the following example:
def squareroot(n):
root = n/2
for k in range(20):
root = (1/2)*(root + n / root)
return root
My question is, the variable 'root' is being reassigned within a for-loop so that with each iteration the value of 'root' within the expression to the right of the assignment operator changes. I'm not sure I understand how this is possible.
Once a function call is made, the 'root' variable outside the for-loop (on line 2) evaluates to a value, which is then referred to by the 'root' variables in the expression of the for-loop block, allowing the expression to evaluate to a single value which is re-assigned to the variable 'root', to the left of the assignment operator, in the for-loop block. At the start of the next iteration, 'root' is no longer n/2, but whatever value the expression in the for-loop has evaluated to. In this case, the variable 'root' has been reassigned a float value and is therefore no longer what it was originally defined -- an expression using 'root' variables.
For example, if we use the function call squareroot(9), 'root' would hold the value of 3.25 after the first iteration, because the expression in the for-loop evaluates to that value. Once the variable 'root', in the for-loop, has been reassigned a single float value, the expression, which originally defined 'root' is destroyed. 'root' has since been redefined as 3.25. 'root', in the for-loop, no longer refers to an expression, but to a single float value. It seems, however, that in this example, the 'root' variable in the for-loop has two meanings following each iteration: it's both a float value and an expression. I don't understand how that can be.