Search code examples
pythoncsvmultiplication

CSV python code: multiplying variables


So far this is my code:

with open("products.txt", "r") as productsFile:
    GTIN8 = input("Enter your GTIN-8 product code: ")
    productsFileReader = csv.reader(productsFile)
    for row in productsFileReader:
        for field in row:
            if field == GTIN8:
                print (row) #displays the product details
                price1= (row[4])
                quantity= (int(input("how many of these would you like to purchase?:")))
                totalprice= quantity * price1 #multiplies quantity by price
                print (totalprice)

I am currently trying to multiply the variable of 'price1' by the 'quantity' which will be entered by the user. price1 is from a row in a csv txt.file I have created.

Every time I run the program, the multiplied price (for example if it were £2.50) displays as "£2.50£2.50£2.50".

How can I make my python code multiply variables together?

thanks

^Thankyou to all who has helped: now it works howver I have another issue...**

productsFileReader = csv.reader(productsFile)
for row in productsFileReader:
    for field in row:
        if field == GTIN8:
            item1= print (row)#displays the product details
            price1= (row[4])
            quantity= (int(input("how many of these would you like to purchase?:")))
            totalprice= quantity * float(price1.replace("£", "")) #multiplies quantity by price
            print (totalprice)
print("Thankyou, your item will cost: "+totalprice)

now when I try to display the price at the end of my program an error of:

TypeError: Can't convert 'float' object to str implicitly

from my understanding, I need to make the float (what I changed before) into an integer so that my code can display a price. but how?
many thanks once again


Solution

  • price1 is a string, and you are multiplying it by an int, which will just result in the string being concatenated n times.

    >>> animal = "cat"
    >>> animal*4
    'catcatcatcat'
    

    You need to convert price1 to a float before it can be multiplied by an int to get the expected result. This is done through the float function. However, if you call float on your price string you will get a ValueError because of the £ symbol, so you must first remove it using str.replace like so:

    >>> price = "£2.50"
    >>> price = price.replace("£", "")
    >>> float(price)
    2.5
    

    Integrating this into your code:

    price1 = row[4]
    quantity = int(input("how many of these would you like to purchase?:"))
    totalprice = quantity * float(price1.replace("£", "")) # multiplies quantity by price