Python Forum

Full Version: [Solved]Help Adding results from for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I'm trying to multiply the Quantity*Price for each row then add them all up to get the total value of all the items I have.

This is what I have so far:
    def calculate_value(self):
        for row in range(self.InventoryDisplay.model().rowCount()):
            QuantityValue = float(self.InventoryDisplay.model().index(row, 2).data())
            PriceValue = float(self.InventoryDisplay.model().index(row, 3).data())
            QuanityPriceValue = QuantityValue*PriceValue
            print(QuanityPriceValue)
My output:
Output:
89.0 0.0 75.0 200.0 32.5 20.0 20.0 4000.0 100.0
The part I'm having trouble with is how do I add all my QuanityPriceValue's that were spit out from that for loop so I can get the combined total (In this case it should be: 4,516.5)?

Thanks in advance.
I don't have the values ​​from your table, so a generic example

prices = [33, 34.55, 45.12]
quantities = [2, 1, 5]
total_price = 0.0

def calculate_value():
    total_price = 0.0
    for row in range(len(prices)):
        QuantityValue = float(prices[row])
        PriceValue = float(quantities[row])
        QuanityPriceValue = QuantityValue*PriceValue
        print("QuanityPriceValue:", QuanityPriceValue)
        total_price += QuanityPriceValue
    print("total price:",total_price)

calculate_value()  
Output:
QuanityPriceValue: 66.0 QuanityPriceValue: 34.55 QuanityPriceValue: 225.6 total price: 326.15
(Jun-24-2022, 04:56 PM)Axel_Erfurt Wrote: [ -> ]I don't have the values ​​from your table, so a generic example

prices = [33, 34.55, 45.12]
quantities = [2, 1, 5]
total_price = 0.0

def calculate_value():
    total_price = 0.0
    for row in range(len(prices)):
        QuantityValue = float(prices[row])
        PriceValue = float(quantities[row])
        QuanityPriceValue = QuantityValue*PriceValue
        print("QuanityPriceValue:", QuanityPriceValue)
        total_price += QuanityPriceValue
    print("total price:",total_price)

calculate_value()  
Output:
QuanityPriceValue: 66.0 QuanityPriceValue: 34.55 QuanityPriceValue: 225.6 total price: 326.15


Thanks! That's exactly what I was looking for.