Reputation: 23
I am wondering how I can output the "total value" of my inventory, and have only been able to successfully extract the numbers I want from the txt file using this code:
def value():
stock_value = open("stock.txt")
for line in stock_value.readlines():
N = re.compile(r'(\d+)|-Side')
n = N.findall(line)
print(n)
For the input file, the first number of each line is the "price", and the second number is "quantity". I wish to multiply the price by quantity of each line, and then sum the total up and output into a total value. How can I do this?
My input file is:
Lion, 10, 2, Cat
Persian, 19, 4, Cat
I am trying to get my output to look something like this:
Total value:
Upvotes: 1
Views: 70
Reputation: 836
We just multiply and sum it and return the value.
def value():
stock_value = open("stock.txt")
result = 0 # init sum as 0
for line in stock_value.readlines():
N = re.compile(r'(\d+)|-Side')
n = N.findall(line)
result += float(n[0]) * float(n[1]) # multiply two values and add to result
return result
Upvotes: 1