意外参数将字典传递给具有**kwargs python3.9的函数

2024-10-01 15:33:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用**kwargs将字典传递给名为solve_slopeint()的函数,因为字典中的值有时可能为无,具体取决于用户输入。当我尝试这样做时,我得到一个打字错误,上面写着:

solve_slopeint() takes 0 positional arguments but one was given

以下是发生的整个过程:

  1. arg_dict值设置为None,程序询问问题
  2. 用户说是的。然后调用一个函数并以另一个问题开始。用户输入2
  3. 要求用户输入点1,然后要求用户输入点2
  4. 这两个点作为列表列表返回给父函数
  5. arg_dict访问这些值并将其设置为相应的键
  6. 使用arg\u dict作为参数调用solve\u slopeint()

以下是您需要查看的代码:

main.py

def slope_intercept():
    arg_dict = {
        "point1": None,
        "point2": None,
        "slope": None,
        "y-intercept": None
    }
    while True:
        question1 = input("Were you given any points that the line passes through? (y/n): ")
        if question1 == 'y':
            point_list = passing_points()
            if len(point_list) == 2:
                arg_dict["point1"] = point_list[0]
                arg_dict["point2"] = point_list[1]
                solve_slopeint(arg_dict)

函数.py

def passing_points():
    while True:
        num_points = input("How many points were you given?: ")
        try:
            num_points = int(num_points)
        elif num_points == 2:
            point1_list = []
            point2_list = []

            while True:
                point1 = input("Enter point 1 in the format x,y: ")
            while True:
                point2 = input("Enter point 2 in the format x,y: ")
    return [point1_list, point2_list]

求解函数.py

def solve_slopeint(**kwargs):
    print("Equation solved!")

Click Here 以查看PyCharm中调试器的输出

大家都知道,我遗漏了很多错误检查,以确保用户不会有意或无意地输入错误的内容。如果我遗漏了一些代码,使得这里的代码不可理解,请在评论中告诉我

有人知道如何解决这个问题吗


Tags: 函数用户nonetrueinputargdictpoints
1条回答
网友
1楼 · 发布于 2024-10-01 15:33:52

调用solve_slopeint函数时出错

这样做:

def slope_intercept():
    arg_dict = {
        "point1": None,
        "point2": None,
        "slope": None,
        "y-intercept": None
    }
    while True:
        question1 = input("Were you given any points that the line passes through? (y/n): ")
        if question1 == 'y':
            point_list = passing_points()
            if len(point_list) == 2:
                arg_dict["point1"] = point_list[0]
                arg_dict["point2"] = point_list[1]
                solve_slopeint(**arg_dict)
                # Or:
                # solve_slopeint(point1=point_list[0], point2=point_list[1])

相关问题 更多 >

    热门问题