Python Forum
ValueError: could not convert string to float: 'Pencil'
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ValueError: could not convert string to float: 'Pencil'
#1
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?
Reply
#2
please, always show entire error message, it makes analysis so much easier.
Reply
#3
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
Reply
#4
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.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  string to float conversion fails PetarPetrenko 10 1,042 Feb-29-2024, 04:20 PM
Last Post: deanhystad
  Convert multiple decimal numbers in string to floats Katy8 6 3,565 Aug-16-2020, 06:06 PM
Last Post: Katy8
  Error could not convert string to float: deadendstreet 4 5,399 Oct-02-2019, 05:49 PM
Last Post: ichabod801
  how to convert list into string Shevach 3 2,632 May-14-2019, 09:51 AM
Last Post: perfringo
  Convert string to a specific number of bytes artblinked 1 2,429 Mar-28-2019, 08:43 PM
Last Post: Larz60+
  How to convert boolean "True" to custom string? student8 3 12,594 Oct-01-2017, 06:24 AM
Last Post: hbknjr
  pandas convert to tuple & float to float64 metalray 6 17,740 Feb-27-2017, 12:50 PM
Last Post: metalray

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020