Python 不支持的操作数类型,带浮点数的逗号
我试图从用户输入中收集一个数字量,将其转换为浮点,在浮点中添加逗号,然后再次将其转换为字符串,以便使用Python打印它 这是我的密码:Python 不支持的操作数类型,带浮点数的逗号,python,types,comma,operand,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("- Pleas
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((现金金额/贴现率),2)”关联的“不支持的操作数类型”。我是否必须在添加逗号后将现金金额转换回浮点数?谢谢 您的代码可以缩短为以下内容:
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((现金金额/贴现率),2)
而不使用您指定的第一个npv
值
cash\u amt=“{}”。format(cash\u amt)
导致您的错误,因此您可以删除它并在最终打印报表中进行格式化。回溯中的确切错误是什么?我更新了我的问题以显示确切的错误。干杯移动cash\u amt=“{:,}”。格式化(cash\u amt)
到打印对账单之前,但实际上您应该在打印对账单中格式化它,您还将npv
更改为浮动,而不是在重新分配到轮((现金金额/折扣率),2)
@philipmcquity,欢迎您。我添加了${.2f}
,因此输出中始终有两位小数,因此4.0
将变为4.00
等。。