【发布时间】:2020-06-23 19:47:27
【问题描述】:
我在 python 中编写了一个程序来查找复利(更像是复制的)。这个程序是用python 2编写的,我在最后一行.format(years)遇到了问题。
我需要知道我可以使用此代码做什么,以及如何在 Python 3 中正确编写它。还有最后一行中的 {} 部分。我应该将其更改为%s 吗?错误说:
"AttributeError: 'NoneType' 对象没有属性 'format'"。
我的代码如下所示:
# Estimated yearly interest
print ("How many years will you be saving ? ")
years = int(input("Enter the number of years : "))
print("How much money is currently in your account ? ")
principal = float(input("Enter current amount in account : "))
print("How much money do you plan on investing monthly ? ")
monthly_invest = float(input("Monthly invest : "))
print("What do you estimate the interest of this yearly investment would be ? ")
interest = (float(input("Enter the interest in decimal numbers (10% = 0.1) : ")))
print(' ')
monthly_invest = monthly_invest * 12
final_amount = 0
for i in range(0, years ):
if final_amount == 0:
final_amount = principal
final_amount = (final_amount + monthly_invest) * (1 + interest)
print("This is how much money you will have after {} years: ").format(years) + str(final_amount)
【问题讨论】:
-
括号应该在末尾而不是字符串文字之后。此外,使用数学公式会更容易
-
我想如果您查看 Python 文档,您会发现格式化字符串是一种完全可以接受的方法。 - docs.python.org/3/library/stdtypes.html#str.format.