[Tutor] Beginner question (variables, namespaces...)
Bob Gailer
bgailer at alum.rpi.edu
Sat Apr 8 02:09:41 CEST 2006
Jesse wrote:
> Why is it that when one variable is assigned a value in terms of
> another variable, assigning a new value to the first doesn't change
> the value of the second? This is giving me a huge headache, since I
> have a bunch of variables defined in terms of one another, and I want
> to be able to dynamically update them (I did not include the
> definitions of the functions overstock and roundup, but they work):
>
> stock = float(raw_input("Enter stock (in terms of portions: "))
> container = float(raw_input("Enter portions per container: "))
> price_per_container = float(raw_input("Enter price per container: "))
> weekly_quota = float(raw_input("Enter quota (in terms of portions): "))
> extra = overstock(stock, weekly_quota) # overstock returns 0 if the
> first argument is less than the second; otherwise it returns the
>
> difference between the first argument and the second.
> need = weekly_quota - extra
> buy_containers = roundup(need/container) # roundup rounds a
> non-integer to the next highest integer
> buy_portions = buy_containers * container
> leftover = buy_portions - need
> cost = price_per_container * buy_containers
>
> I would like to write a function that will update the values of the
> above variables given an increase in only the stock variable.
> Otherwise I'd have to repeat a bunch of code...:(
def recalculate():
global extra, need, buy_containers, buy_portions, leftover, cost
extra = overstock(stock, weekly_quota)
need = weekly_quota - extra
buy_containers = roundup(need/container)
buy_portions = buy_containers * container
leftover = buy_portions - need
cost = price_per_container * buy_containers
That's all there is to it.
More information about the Tutor
mailing list