Home > Enterprise >  How to remove the UnboundLocalError in Python while calculating profit from the values given in a di
How to remove the UnboundLocalError in Python while calculating profit from the values given in a di

Time:11-30

I have a dictionary dt which consists of cost price, selling price and the inventory. The purpose of the code is to calculate the Profit. Profit and can be calculated by Profit = Total selling price - Total Cost price. For example following is the input profit({ "cost_price": 32.67, "sell_price": 45.00, "inventory": 1200 }) And it's output is 14796. To calculate individual Total cost the formula is Total cost price = inventory * cost_price and Total Selling Price = inventory * sell_price. Below is my code and the error.

 class Solution(object):

    def total_profit(self, di):

        global total_selling_price
        global total_cost_price
        for k, v in enumerate(di):
            if k == 'cost_price':
                cp = di[v]
            elif k == 'inventory':
                inventory = di[v]
                total_cost_price = cp * inventory
            else:
                sp = di[v]
                total_selling_price = sp * inventory

        profit = total_selling_price - total_cost_price

        return profit


if __name__ == '__main__':
    p = Solution()
    dt = {"cost_price": 2.77,
          "sell_price": 7.95,
          "inventory": 8500}
    print(p.total_profit(dt))

Error shown is as follows

    Traceback (most recent call last):
  File "/Users/tejas/PycharmProjects/LeetcodeinPython/EdbatsQuestions/Profit.py", line 27, in <module>
    print(p.total_profit(dt))
  File "/Users/tejas/PycharmProjects/LeetcodeinPython/EdbatsQuestions/Profit.py", line 15, in total_profit
    total_selling_price = sp * inventory
UnboundLocalError: local variable 'inventory' referenced before assignment

CodePudding user response:

When extracting values from the dictionary you need to validate their existence. You may even want to check the data type(s).

There is no need for global variables in this case.

The main method might as well be static as it does not depend upon any other attributes of the Solution class.

Something like this will suffice and be more robust:

class Solution:
    @staticmethod
    def total_profit(di):
        cp = di.get('cost_price')
        sp = di.get('sell_price')
        iv = di.get('inventory')
        if cp and sp and iv:
            return (sp - cp) * iv
        # implicit return of None if any keys unavailable


dt = {"cost_price": 2.77,
      "sell_price": 7.95,
      "inventory": 8500}

print(Solution.total_profit(dt))

Output:

44030.0

CodePudding user response:

In your first "elif" block indeed the inventory variable is unbound (it hasn't been defined before). The line earlier you just checked if k is equal to string "inventory", but as explained below it never is in your case.

TLDR; Ain't somebody learning for a interview huh? :D By default if you loop over a dictionary you are looping over its keys. Enumerate yields idx of an iterable and its value. So you are mixing stuff here.

This (compare with your case please):

   x = {"a":5, "b":77}
   for k,v in enumerate(x):
       print(k,v)

Will print for you:

   0, "a"
   1, "b"

Rather not what you are aiming at. So iterate using .items(), which will give you pairs of key, value on each loop iteration.

  • Related