omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    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

    Pythonista
    3
    4
    3572
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Bjucha
      Bjucha last edited by omz

      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?

      1 Reply Last reply Reply Quote 0
      • omz
        omz last edited by

        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).

        1 Reply Last reply Reply Quote 0
        • ccc
          ccc last edited by 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))
          
          1 Reply Last reply Reply Quote 0
          • Bjucha
            Bjucha last edited by

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

            1 Reply Last reply Reply Quote 0
            • First post
              Last post
            Powered by NodeBB Forums | Contributors