You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 19:59:56