Home > Mobile >  could not convert string to float "price"
could not convert string to float "price"

Time:11-05

when I run the program this has been popping up. could not convert string to float. I tried to look it up but I couldn't find anything.

here's the code:

f = open("ticket.txt",'r')
s=f.read()
lines=s.split("\n")
priceMax=0
priceMin=9999
total=0
for line in lines:
cols=line.split(" ")
price=(float)(cols[1])
total=total price
if(price>priceMax):
   priceMax=price
if(price<priceMin):
   priceMin=price
f.close()
f=open("output.txt",'w')
f.write("*******************************************\n")
f.write(" TICKET REPORT\n")
f.write("*******************************************\n\n")
f.write("There are "   str(len(lines))   " tickets in the database.\n\n")
f.write("Maximum Ticket price is $"   str(priceMax)   "\n")
f.write("Minimum Ticket price is $"   str(priceMin)   "\n")
f.write("Average Ticket price is $"   str(total / len(lines))   "\n\n")
f.write("Thank you for using our ticket system!\n\n")
f.write("*******************************************\n")

f.close()
print("File Created sucessfully")

CodePudding user response:

Yeah, indentation is important in Python. You must be consistent.

This "cast" (float) evaluates to, basically, the float() function, and then you call it, so that's not the problem. More canonical is f = float("123.45"). Now, this will throw a ValueError exception if there's an invalid number passed, so, you might want to catch this, so you can find out where the problem is. Along the lines of:

s = "123.baboom"
try:
    f = float(s)
except ValueError as e:
    print("Oh, no, got an exception:", e)
    print("The offending string was: ", s)

CodePudding user response:

What's the error that's shown?

I think the issue is that you have started the list with cols[1] instead of cols[0].

Also the indentation is wrong here.

for line in lines:
    cols=line.split(" ")
    price=(float)(cols[0])
    total=total price

    if(price>priceMax):
       priceMax=price

    if(price<priceMin):
       priceMin=price
  • Related