Home > Enterprise >  Using a variable in a dictionary to find total cost of an item cart and printing in ascending order
Using a variable in a dictionary to find total cost of an item cart and printing in ascending order

Time:09-28

Currently, I have two functions and am trying to use both to find the total cost of all user inputs which are stored in a dictionary.

In the cart_cost function it comes up with UnboundLocalError: local variable 'total_price' referenced before assignment but still runs the code anyway.

it also seems to only add the first item and not the resr is there a way I can keep adding the total cost for both quanities over 10 and ones that don't. For example: In addition to the function, is there a possiblity to show all of the items in acending order based on the code number. At the moment it is only showing the last inputed record for the print list.

Example of inputs

enter image description here

What i believe it should be

11 * 12.95 * 0.9 = 128.205 

29.95 * 8  = 239.60

54.95 * 25 * 0.9 = 1236.375

total cost = 1604.18

Thank you

The code:

productList = ['Salad Server Set', 'Party Serviette Holder', 'Tea Set', 'Mixing Bowl Set', 'Knife Block Set',
           'Coffee Capsule Holder', 'Plastic Sensor Soap Pump', 'Storage Bucket', 'Oven Glove', 'Apron', 
           'Biscuit Barrel', 'Chopping Board', 'Carioca Cups', 'Soup Bowls', 'Elevate Wood Turner', 
           'Pasta Machine', 'Teapot', 'Cake Pop Scoop', 'Cookbook Stand', 'Chocolate Station', 'Coffee Maker', 
           'Pepper Mill', 'Salt Mill', 'Glass Storage Jar', 'Measuring jug', 'Kitchen Scale', 'Tenderiser', 
           'Pizza Docker', 'Knife Sharpener', 'Steel Cork Opener', 'Steel Garlic Press', 'Steel Can Opener', 
           'Stainless Steel Crank Flour Sifter', 'Mineral Stone Mortar and Pestle', 'Citrus Cather', 
           'Cherry & Olive Pitter', 'Multi Grater-Detachable', 'Stainless Steel Colander', 'Steel Pizza Pan', 
           'Pop Container'];

priceList = [18.70, 11.95, 39.95, 49.95, 99.95, 29.95, 79.95, 24.95, 9.95, 29.95, 39.95, 12.95, 54.95,
         43.00, 19.95, 144.95, 29.95, 9.95, 29.95, 34.95, 29.00, 84.94, 84.95, 4.95, 19.95, 39.95, 34.95, 
         19.95, 79.95, 36.95, 34.95, 36.95, 33.95, 74.95, 19.95, 27.95, 26.95, 44.95, 12.95, 22.95]; 

def shop():
    number_input = []
    amount_inputed = []
    while True:
        number_result = NUMBER()
        amount_result = AMOUNT()
        if number_result=="END":
            print("Canceled by user")
            break
        elif number_result and not(amount_result):
            print("Invalid Quanity")
            break
        elif not(number_result) and amount_result:
            print ("Invalid code")
            break 
        elif not(number_result) and not(amount_result):
            print("invalid input")
            break
        else:
            number_input.append(int(number_result))
            amount_inputed.append(int(amount_result))
    return number_input,amount_inputed


#start with an empty dictionary then add the inputted items based on the code_inputed, code_inputed is used as the index

def sorted_records(code_inputed, quan_inputed):
    product_info = {}
    print('{:<12}\t{:<40}{:<20}'.format("code", "product", "Price $"))
    print('{:<12}\t{:<40}{:<20}'.format("----", "------------------------------------", "-------"))
    for kk in range(len(code_inputed)):
        total = 0
        quan = quan_inputed[kk]
        kk = code_inputed[kk]
        price = priceList[kk]
        product = productList[kk]
        if kk not in product_info:
            product_info[kk] = [kk, quan, price, product]
        else:
            product_info[kk][1]  = quan
            product_info[kk][1] = product_info[kk][1] 
    print()
    print('{:<12}\t{:<40}{:<20}'.format(kk, quan, price))
    #for x in product_info:
    # for info in product_info[x]:
    #    print(info, end="     ")
    #print()
    return product_info
    

def cart_cost(code_inputed, quan_inputed):
    sorted_records(code_inputed, quan_inputed)
    member = is_member()
    inital_cost = 0 
    club_discount = 0 
    total_cost = 0 
    discont = 0.1
    for kk in range(len(code_inputed)):
        quan = quan_inputed[kk]
        kk = code_inputed[kk]
        price = priceList[kk]
        product = productList[kk]
        if member == "YES" and quan >= 10:
            print(product)
            club_discount = quan * price * 0.9
            print(club_discount)
            total_price  = club_discount
            return club_discount
        else:
            total_cost  = quan * price
            return club_discount
    print(club_discount)

Error:

UnboundLocalError: local variable 'total_price' referenced before assignment

Input code_inputed = [4, 8, 3, 24, 4]

quan_inputed = [6, 4, 11, 5, 8]

CodePudding user response:

In one place you have total_price but it should be total_cost and this make problem.

In sorted_records() you should use print() inside for-loop.

In cart_cost() you shouldn't use return club_discount because it finishs loop.


Full working example with other changes.

I use zip() instead of range(len(...)).
I use more readable name code instead of kk

def sorted_records(code_inputed, quan_inputed):
    product_info = {}
    
    print('{:<12}\t{:<40}{:<20}'.format("code", "product", "Price $"))
    print('{:<12}\t{:<40}{:<20}'.format("----", "------------------------------------", "-------"))
    
    #for index in range(len(code_inputed)):
    #    quan = quan_inputed[index]
    #    code = code_inputed[index]

    for quan, code in zip(quan_inputed, code_inputed):

        price = priceList[code]
        product = productList[code]
        
        if code not in product_info:
            product_info[code] = [code, quan, price, product]
        else:
            product_info[code][1]  = quan
            product_info[code][2] = product_info[code][1]
            
        print('{:<12}\t{:<40}{:<20}'.format(code, quan, price))
        
    return product_info
    
def is_member():
    return "YES"

def cart_cost(code_inputed, quan_inputed):
    sorted_records(code_inputed, quan_inputed)
    
    member = is_member()
    club_discount = 0 
    total_cost = 0 
    #discont = 0.1
    
    #for index in range(len(code_inputed)):
    #    quan = quan_inputed[index]
    #    code = code_inputed[index]

    for quan, code in zip(quan_inputed, code_inputed):
        
        price = priceList[code]
        product = productList[code]
        
        if member == "YES" and quan >= 10:
            club_discount = 0.9
        else:
            club_discount = 1
            
        total_cost  = quan * price * club_discount

    total_cost = round(total_cost, 2)
    print("total cost:", total_cost)
    #print(f"total cost: {total_cost:.2f}")
    
    return total_cost
 
# --- main --- 
   
priceList = {
    38: 12.95,
    5: 29.95,
    12: 54.95,
}

productList = {
    38: 12.95,
    5: 29.95,
    12: 54.95,
}  
  
code_inputed = [12, 5, 38]
quan_inputed = [25, 8, 11]

cart_cost(code_inputed, quan_inputed)

Result:

code            product                                 Price $             
----            ------------------------------------    -------             
12              25                                      54.95               
5               8                                       29.95               
38              11                                      12.95               
total cost: 1604.18
  • Related