pythontypesnumber-formattingoperands

Unsupported operand types, commas with floats


I am trying to gather an number amount from user input, convert it to a float, add commas to the float, and then convert it to a string again so I can print it using Python.

Here is my code:

usr_name = raw_input("- Please enter your name: ")
cash_amt = raw_input("- " + usr_name +", please enter the amount of money to be discounted: $")
discount_rate = raw_input("- Please enter the desired discount rate: ")
num_years = raw_input("- Please enter the number of years to discount: ")
npv = 0.0

usr_name = str(usr_name)

cash_amt = float(cash_amt)
cash_amt = round(cash_amt, 2)
cash_amt = "{:,}".format(cash_amt)

discount_rate = float(discount_rate)
num_years = float(num_years) 
npv = float(npv)

discount_rate = (1 + discount_rate)**num_years
npv = round((cash_amt/discount_rate), 2)
npv = "{:,}".format(npv)

print "\n" + usr_name + ", $" + str(cash_amt) + " dollars " + str(num_years) + " years from now 
at adiscount rate of "  + str(discount_rate) + " has a net present value of $" + str(npv)

I am getting a "Unsupported operand type" tied to "npv = round((cash_amt/discount_rate), 2)" when I try to run it. Do I have to convert cash_amt back to a float after adding the commas? Thanks!


Solution

  • Your code can be shortened to the following:

    usr_name = raw_input("- Please enter your name: ")
    cash_amt = raw_input("- " + usr_name +", please enter the amount of money to be discounted: $")
    discount_rate = raw_input("- Please enter the desired discount rate: ")
    num_years = raw_input("- Please enter the number of years to discount: ")
    
     #  usr_name is  already a string
    cash_amt = float(cash_amt)
    cash_amt = round(cash_amt, 2)
    
    
    discount_rate = float(discount_rate)
    num_years = int(num_years) # we want an int to print, discount_rate  is a float so our calculations will be ok.
    
    discount_rate = (1 + discount_rate)**num_years
    npv = round((cash_amt/discount_rate), 2)
    
    
    print "\n{}, ${:.2f}  dollars {} years from now at discount rate of {:.2f} has a net " \
    "present value of ${}".format(usr_name,cash_amt,num_years,discount_rate,npv)
    

    npv = float(npv) is never actually used as you then do npv = round((cash_amt/discount_rate), 2) without using the first npv you assign a value to.

    cash_amt = "{}".format(cash_amt) is causing your error so you can just remove it and do the formatting in your final print statement.