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

Python3.9中使用**kwargs传递字典至solve_slopeint()函数时触发TypeError的技术问询

修复TypeError并完善代码的方案

首先,咱们先搞定你遇到的核心TypeError问题:

你定义的solve_slopeint(**kwargs)是接受关键字参数的,但你调用的时候直接传了一个字典arg_dict作为位置参数,Python就会认为你给了一个它没预期的位置参数,所以抛出那个错误。

核心修复:解包字典传递参数

把调用代码从:

solve_slopeint(arg_dict)

改成:

solve_slopeint(**arg_dict)

用**操作符把字典里的键值对拆成key=value的形式传递给函数,这样就完全符合**kwargs的参数要求了。


顺便修复passing_points()里的逻辑问题

看你贴的代码,这个函数还有几个会导致功能异常的问题,得一起调整:

  1. try-except语法错误:你写的try:块后面直接跟了elif num_points == 2:,这是不符合语法的,应该用if判断转换后的整数,同时要加except块处理输入非整数的情况。
  2. 无限循环死锁:输入point1和point2的while True循环没有退出条件,会一直让用户输入,永远不会返回结果。
  3. 未收集输入值:你定义了point1_list和point2_list,但没有把用户输入的x、y值添加进去,最后返回的是空列表。

修复后的passing_points()可以改成这样:

def passing_points():
    while True:
        num_points = input("How many points were you given?: ")
        try:
            num_points = int(num_points)
            if num_points == 2:
                # 处理点1的输入
                point1_list = []
                while True:
                    point1 = input("Enter point 1 in the format x,y: ")
                    try:
                        x, y = map(float, point1.split(","))
                        point1_list = [x, y]
                        break  # 输入正确就退出循环
                    except ValueError:
                        print("请按照x,y的格式输入,比如3,5")
                # 处理点2的输入
                point2_list = []
                while True:
                    point2 = input("Enter point 2 in the format x,y: ")
                    try:
                        x, y = map(float, point2.split(","))
                        point2_list = [x, y]
                        break
                    except ValueError:
                        print("请按照x,y的格式输入,比如3,5")
                return [point1_list, point2_list]
            else:
                print("目前只支持处理2个点的情况,请输入2")
        except ValueError:
            print("请输入有效的数字(比如2)")

验证修复效果

当你用**arg_dict传递参数后,solve_slopeint里的kwargs就会是一个包含point1、point2等键的字典,你可以在函数里正常使用这些值,比如补全计算逻辑:

def solve_slopeint(**kwargs):
    point1 = kwargs.get("point1")
    point2 = kwargs.get("point2")
    if point1 and point2:
        # 计算斜率和截距
        slope = (point2[1] - point1[1]) / (point2[0] - point1[0])
        y_intercept = point1[1] - slope * point1[0]
        print(f"直线的斜截式方程是: y = {slope}x + {y_intercept}")
    print("Equation solved!")

这样就能正常运行啦~

内容的提问来源于stack exchange,提问作者Matthew Schell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 06:48:12