Reputation: 11
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
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
Reputation: 13175
There are a couple of issues:
("")
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.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