Python 为什么打印时格式错误?
那么这个,Python 为什么打印时格式错误?,python,error-handling,Python,Error Handling,那么这个, account_balance = {'a': '122.8', 'b': '14.1', 'c': '31.44', 'd': '15.15', 'e': '23.07'} total = 0.00 for key in account_balance: total += float(account_balance[key]) 抛出以下错误: AttributeError:“非类型”对象没有属性“格式” 。。。为什么?应该是: print("TOTAL: {0}").fo
account_balance = {'a': '122.8', 'b': '14.1', 'c': '31.44', 'd': '15.15', 'e': '23.07'}
total = 0.00
for key in account_balance:
total += float(account_balance[key])
抛出以下错误:
AttributeError:“非类型”对象没有属性“格式”
。。。为什么?应该是:
print("TOTAL: {0}").format(str(total))
您的原始代码正在尝试调用.format()
方法以打印函数的返回值。因为它总是None
,所以您会得到一个AttributeError
如果您使用的是Python=3.6
,我建议您使用它。它们使用起来非常好,将使字符串格式化成为一种乐趣:
print("TOTAL: {0}".format(str(total)))
此外,该代码:
print(f"TOTAL: {total}")
通过使用sum
,可以简化并提高效率:
或者使用sum
和map
:
total = sum(float(value) for value in account_balance.values())
因此,为了使您的代码美观、易于阅读,我们将:
total = sum(map(float, account_balance.values()))
输出:
总计:206.56
您可能想试试这个:
账户余额={'a':'122.8','b':'14.1','c':'31.44','d':'15.15','e':'23.07'}
总计=0.00
对于关键账户余额:
总计+=浮动(账户余额[关键])
打印(总计)
206.56
您在print()
上调用的是.format()
,而不是在字符串上。我建议使用f字串。最后的答案是:打印(“总计:{0}”。格式(总计)),与打印(“总计:{0}”)。格式(总计))为什么不account\u balance.values()
尽管如此?@SayandipDutta-Yeah刚刚意识到我自己也一样,修正:)
total = sum(map(float, account_balance.values()))
account_balance = {'a': '122.8', 'b': '14.1', 'c': '31.44', 'd': '15.15', 'e': '23.07'}
total = sum(float(value) for value in account_balance.values())
print(f"TOTAL: {total}")