Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Could not convert string to float
-
Hi
Im trying to create a budget program that you put your incomes in and then you add all your bills. However im far from finish due to the issue: "Could not convert string to float"Here is the code:
sum = '0' while True: print('Enter income, if no more income press enter') income = input() sum = float(income) + float(sum) <-- here is where the issue appears: print(sum) if income ==' ': break print('Your total income is:' +sum)
Why can't it not convert to float?
-
One problem is that you cannot convert an empty string (
''
) to a number, so the last conversion ofincome
(when you press enter) will fail. You could move theif
statement (if income == ' '
) above the addition to avoid this issue. You should also check for an empty string there, not one space.The next issue you'll encounter will be that the final
print
will raise aTypeError
("Can't convert 'float' object to str implicitly"). This is becausesum
is a number after your loop and you cannot add numbers and strings. Possible solution:print('Your total income is:' + str(sum)
. -
#!/usr/bin/env python3 prompt = 'Enter income, if no more income press enter: ' total = 0 # avoid using the word 'sum' because sum() is a Python builtin function while True: income = input(prompt).strip() if not income: break total += float(income) print('Your total income is: ${:,.2f}'.format(total))
-
Thanks for the all the help. Gonna try it tonight!