Python Forum

Full Version: ValueError: could not convert string to float: 'Pencil'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
def sortSales(filename):
    with open(filename, 'r') as f:
        f.readline() # skip header
        d = {}
        for line in f:
            if len(line) > 0:
                words = line.strip().split(',')
                name = words[1]
                sales = float(words[3]) * float(words[4])
                d[name] = sales
        items = [(sale, name) for name, sale in d.items()]
        items.sort()
        items.reverse()
        for sale, name in items:
            print('{:<10}: ${:>8,.2f}'.format(name, sale))
I'm getting an error saying ValueError: could not convert string to float: 'Pencil' for sales = float(words[3]) * float(words[4]. What do I need to do to fix it?
please, always show entire error message, it makes analysis so much easier.
ValueError: could not convert string to float: 'Pencil' is the entire error message. I'm trying to get this output
İmage


İmage

with this ifile
Please do not post images. Refer to the Help document on BBCode for instructions on how to properly post code, errors and output. It would also be helpful if you post one or two lines of the file you are reading from.

The error is telling you it cannot convert the string "Pencil" into a number. Are you remembering that lists start with 0 and not 1?

Prior to doing any calculations use print statements to see what values words[1], words[3] and words[4] actually contain.