0

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!

4

1 回答 1

1

您的代码可以缩短为以下内容:

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)永远不会像您在npv = round((cash_amt/discount_rate), 2)不使用npv 您分配值的第一个的情况下那样实际使用。

cash_amt = "{}".format(cash_amt)导致您的错误,因此您可以将其删除并在最终打印语句中进行格式化。

于 2014-09-15T19:40:46.047 回答