Passing Values
Remco Gerlich
scarblac at pino.selwerd.nl
Tue Feb 13 18:06:50 EST 2001
mike.mellor at tbe.com <mike.mellor at tbe.com> wrote in comp.lang.python:
> I am working on an RPN calculator program, using a four level stack.
> I initialize it as:
>
> stack = [0.0,0.0,0.0,0.0]
>
> I am noticing problems with the following two functions (xStack and
> yStack are Entry widgets). clearer is supposed to clear the values
> of the stack, and RollDown is supposed to "roll the stack" down.
>
> def clearer(event):
> yStack.delete(0,END)
> xStack.delete(0,END)
> stack = [0.0, 0.0, 0.0, 0.0]
> print 'Clear ' + str(stack)
> for i in range(4):
> print 'Stack ' + `i` + ' ' + str(stack[i])
The stack you use here is a local variable. It has no effect on the global
variable also named stack.
Solution: put 'global stack' as the first line of the function.
> def RollDown(event):
> stack[0] = stack[1]
> stack[1] = stack[2]
> stack[2] = stack[3]
> try:
> stack[3] = float(xStack.get())
> except ValueError:
> stack[3] = 0.0
> xStack.delete(0,END)
> xStack.insert(0,stack[0])
> yStack.delete(0,END)
> yStack.insert(0,str(stack[1]))
> print 'Roll down ' + str(stack)
> for i in range(4):
> print 'Stack ' + `i` + ' ' + str(stack[i])
Here, you never directly assign to stack, so Python assumes you meant the
global. This function uses the global stack.
> The console reports that the stack is cleared, but when I roll the
> stack down, old values pop in. Do I need to use a deepcopy to pass
> the values from one stack location to the next (stack[0] = deepcopy
> (stack[1])) or is there a better way to do this?
Instead of stack[0]=stack[1]; stack[1]=stack[2]; stack[2]=etc, you
simply want to do 'del stack[0]'. Then add the new element with
stack.append(0.0).
--
Remco Gerlich
More information about the Python-list
mailing list