Python代码触发AttributeError问题修复请求(学校项目用)
修复Python代码中的AttributeError错误
你的代码触发AttributeError的核心原因是:print()函数的返回值是None,你却错误地在print的返回值上调用了.format()方法,而None对象没有format属性。
修复后的代码(两种写法)
写法一:使用format方法
a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) print('The product of {first} and {sec} is: {product}'.format(first=a, sec=b, product=a*b)) print('The sum of {first} and {sec} is: {sum_val}'.format(first=a, sec=b, sum_val=a+b))
写法二:使用f-string(更简洁,Python3.6+支持)
a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) print(f'The product of {a} and {b} is: {a*b}') print(f'The sum of {a} and {b} is: {a+b}')
错误点说明
原代码中,你将字符串和计算结果作为两个参数传给print,接着试图在print的返回值(None)上调用format,这完全颠倒了调用顺序。正确的逻辑是:先对包含占位符的字符串调用format方法完成替换,再将替换后的完整字符串传给print函数;或者直接使用f-string在字符串中嵌入变量和表达式,写法更直观。
内容的提问来源于stack exchange,提问作者Rudransh Joshi
相关产品推荐
相关产品推荐

