Leonardo Fonseca
Leonardo Fonseca

Reputation: 11

Error string to float

This is my code. I am doing a beginer execise. When I run the program

I can put the values, but when I go out of the loop the following error message appears:

 a + = float (input ("Enter the product cost"))

ValueError: could not convert string to float:

Can someone help me?

Here it goes:

e = 0.25
f = 0.18
a = 0.0

while True:
    a += float(input("Enter the product cost:  "))
    if a == "":        
        break

b = a*e
c = a*f
d = a+b+c

print ("tax: " + b)
print ("tips: " + c)
print ( "Total: " + d)

Upvotes: 1

Views: 170

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308111

You are combining two operations on the same line: the input of a string, and the conversion of the string to a float. If you enter the empty string to end the program, the conversion to float fails with the error message you see; the error contains the string it tried to convert, and it is empty.

Split it into multiple lines:

while True:
    inp = input("Enter the product cost:  ")
    if inp == "":        
        break
    a += float(inp)

Upvotes: 1

roganjosh
roganjosh

Reputation: 13175

There are a couple of issues:

  1. the check for a being an empty string ("") comes after the attempt to add it to the float value a. You should handle this with an exception to make sure that the input is numerical.
  2. If someone doesn't enter an empty or invalid string, ever, then you get stuck in an infinite loop and nothing prints. That's because the indentation of your b, c, d calculations and the prints is outside of the scope of the while loop.

This should do what you want:

e = 0.25
f = 0.18
a = 0.0

while True:
    try:
        input_number = float(input("Enter the product cost:  "))
    except ValueError:
        print ("Input is not a valid number")
        break
    a += input_number        
    b = a*e
    c = a*f
    d = a+b+c

    print ("tax: ", b)
    print ("tips: ", c)
    print ( "Total: ", d)

Upvotes: 0

Related Questions