Hi fellow stackoverflow'ers,
I'm pretty good with Python but I'm trying to see if there is a better way to do the following. I need to produce a delta to adjust stock levels. I have the following code which works, but could it be done faster/more Pythonic?
a = 100
b = 50
def negativeNumber(x): # From https://stackoverflow.com/a/64445338/22669764
neg = x * (-1)
return neg
if not a == b:
if b < a:
delta_qty = negativeNumber(a - b)
if b > a:
delta_qty = b - a
if b == 0:
delta_qty = negativeNumber(a)
if a == 0 and b == 0:
delta_qty = 0
The above works and produce the following results:
b<a = -50
b>a = 50 (If we swapped the values)
b=0 = -100 (If b=0)
a=0 & b=0 = 0 (I need this to set a variable not shown in example)
Is there is a faster/tidier/more Pythonic way I would achieve the same results?
EDIT: Thanks for the answers and comments, Goku's answer and Homer512 comment look to achieve what I need in a far neater fashion.
If you want negative sign (as you have shown in example) in your result then:
def your_func(a,b):
return b-a # it will give negative when a > b and vice-versa
If you do not want negative sign no matter which is bigger a or b then :
def your_func(a,b):
return abs(b-a)
delta_qty = your_func(a,b)