“NoneType”对象没有属性“format”python字符串

2024-09-26 22:13:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python编写了一个程序来寻找复利(更像是复制的)。这个程序是用python 2编写的,我在最后一行.format(years)遇到了一个问题

我需要知道我可以用这段代码做什么,以及如何用Python3正确地编写它。还有最后一行的{}部分。我应该把它改成%s吗?错误显示:

"AttributeError: 'NoneType' object has no attribute '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)

Tags: theinyouformatinputamounthowfinal
3条回答

您可以像这样执行普通字符串连接:

Print("This is how much money you will have after " + format(years) + " years: " +str(final_amount)

或者,如果您希望保持相同的格式,您可以这样做

print("This is how much money you will have after {} years: ".format(years) + str(final_amount))

改变

print("This is how much money you will have after {} years:  ").format(years) + str(final_amount)

print("This is how much money you will have after {} years:  ".format(years)) + str(final_amount)

format()string类的一个方法。您正在print()函数上使用它,它是NoneType的函数,因此出现了错误

我觉得没有人推荐f-strings有点遗憾。只有在Python3.6之后才有可用的,但是它们非常强大,易于使用,并且推荐使用PEP 498中的字符串格式选项(除非我弄错了)

如果您想认真对待python并与其他人合作,我真的建议您阅读最佳实践,在本例中是f-strings

使用f字符串的解决方案:

print(f"This is how much money you will have after {years} years: {final_amount}")

相关问题 更多 >

    热门问题