deox
deox

Reputation: 265

Dynamically increment/decrement the value of a variable?

I have a situation where the variable max_order is calculated depending on the value of other variables such that sometimes max_order is positive and others negative. Here's my code:

def delta_value(direction):
    diff=value2-value1
    if diff > 0: ascend="+"; descend="-"
    elif diff < 0: ascend="-"; descend="+"
    if direction == "increase": return ascend
    elif direction == "decrease": return descend

def calc_max_order():
    global max_order
    if num < max_num:
        while num < max_num:
            exec("max_order%s=1" % delta_value("decrease"))
    elif num > max_num:
        while num > max_num:
            exec("max_order%s=1" % delta_value("increase"))

This code doesn't seem to work (i.e. it doesn't change the value of max_order), but there are no errors returned. It stays stuck in the while loops. The code does work when calc_max_order is not a function, but in the main block. However, I want to make it a function to clean up my code.

I know that most people say it is unwise to use exec, but I'm just starting to learn python and I'm not sure how else to do it. I suppose I could use a bunch of if statements, but I imagine there is a cleaner way to do it.

So, to be clear, my question is:

Is there a way to either make exec("max_order%s=1" % delta_order_value("decrease")) work inside a function, or is there an alternative method to dynamically increse/decrease max_order depending on the output of delta_value?

Upvotes: 0

Views: 502

Answers (2)

mhlester
mhlester

Reputation: 23251

Change delta_value() to:

def delta_value(direction):
    diff = cmp(value2, value1)   # -1 for <, 0 for ==, 1 for >
    if direction == "increase": diff = -dif
    return diff

...meanwhile...

In place of the exec, you can now have:

max_order = max_order + diff

Diff is either positive or negative, rather than '+' or '-'

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 362197

The use of exec() is a huge red flag. You can do this with a fixed += and a varying delta.

delta = (+1 if ascending else -1)
max_order += delta

And if you need to reverse the sense of delta, negate it:

max_order -= delta;
# or
delta = -delta;
# or
delta *= -1;

Upvotes: 1

Related Questions