不支持的操作数类型,带浮点数的逗号

时间:2014-09-15 19:23:55

标签: python types comma operand

我正在尝试从用户输入中收集一些数量,将其转换为浮点数,向浮点数添加逗号,然后再将其转换为字符串,以便我可以使用Python打印它。

这是我的代码:

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)

当我尝试运行它时,我得到一个“不支持的操作数类型”与“npv = round((cash_amt / discount_rate),2)”相关联。添加逗号后,是否必须将cash_amt转换回浮点数?谢谢!

1 个答案:

答案 0 :(得分: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)导致您的错误,因此您可以将其删除并在最终的打印声明中进行格式化。