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

Python报'function'对象不支持项赋值错误,计算器代码修改咨询

报错原因分析
  1. 命名冲突与作用域错误
    你在全局作用域定义了名为accessories的函数,虽然函数内部也定义了同名的字典变量,但这个字典是仅在函数运行时生效的局部变量,函数外部完全无法访问。当你在while循环中执行accessories["first_number"]= all_nr["The result"]时,解释器识别到的accessories是全局的函数对象,函数本身不支持字典式的键值赋值操作,因此直接抛出TypeError。

  2. 逻辑设计缺陷
    原有accessories函数每次调用都会强制要求用户输入第一个数,没有预留参数入口接收历史计算结果,就算解决了命名冲突,也无法实现「用上一次结果作为下一次计算第一个数」的需求。

解决方案
  1. 分离命名:将函数内部的字典变量改名,避免和函数名冲突,同时给函数增加可选入参,用来接收历史计算结果:如果传入了历史结果,就直接作为本次计算的第一个数,跳过用户输入环节;如果没有传入就正常要求用户输入第一个数。
  2. 调整循环逻辑:不用尝试给函数对象赋值,每次计算完成后保存结果,下次调用accessories函数时直接把结果当参数传入即可。
  3. 修复原有循环的逻辑错误:原有代码选择「no」退出本次计算后,只清屏没有重置历史结果状态,同步修复该问题。
修改后完整可运行代码
from art import logo
print(logo)
from replit import clear

all_nr = {}

def operators(operator, n1, n2):
    if operator == "+":
        result = n1 + n2
    elif operator == "-":
        result = n1 - n2
    elif operator == "*":
        result = n1 * n2
    elif operator == "/":
        result = n1 / n2
    all_nr['The result'] = result
    return round(result, 2)

conti_cal = True
# 给函数增加可选参数,默认值为None,表示没有历史结果
def accessories(last_result=None):
    # 字典改名,避免和函数名冲突
    calc_params = {}
    # 如果有传入历史结果,直接用,不用用户输入
    if last_result is not None:
        calc_params["first_number"] = last_result
        print(f"第一个数为上一次计算结果:{last_result}")
    else:
        calc_params["first_number"] = float(input("What is the first number?: "))
    print(""" +
    -
    *
    / 
    """)
    calc_params["operator"] = input("Pick an operator: ")
    calc_params["second_number"] = float(input("What is your second number?: "))
    return operators(calc_params["operator"], calc_params["first_number"], calc_params["second_number"])

# 初始化历史结果变量
last_res = None
while conti_cal:
    current_res = accessories(last_res)
    print(current_res)
    conti = input("type 'yes' to continue calculate, otherwise type 'no':")
    if conti == "yes":
        # 保存本次结果,下次调用直接传参
        last_res = all_nr["The result"]
    else:
        clear()
        # 选no就重置历史结果,下次重新计算
        last_res = None

内容的提问来源于stack exchange,提问作者Jeanne Baity

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:45:05