Forum Archive

Could not convert string to float

Bjucha

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?

omz

One problem is that you cannot convert an empty string ('') to a number, so the last conversion of income (when you press enter) will fail. You could move the if 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 a TypeError ("Can't convert 'float' object to str implicitly"). This is because sum is a number after your loop and you cannot add numbers and strings. Possible solution: print('Your total income is:' + str(sum).

ccc
#!/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))
Bjucha

Thanks for the all the help. Gonna try it tonight!