我的函数和参数代码有什么问题?

时间:2017-12-03 03:33:10

标签: python python-2.7

我试图运用我所学到的关于功能和参数的知识,所以我想出了一个可以计算学费的代码(纯粹是假设的)

def renting_1(laptop, weeks):
            laptop = 5 * weeks
            if weeks > 10:
                    laptop -= 120
            elif weeks > 5:
                    laptop -= 50
            return laptop

def renting_2(textbooks, number_of_textbooks, weeks):
        textbooks = number_of_textbooks * 20 + (10 * weeks)
        if weeks >= 26:
                textbooks -= (5 * (weeks - 26))
        return textbooks

def school_cost(cost, weeks):
        cost = 200 * weeks
        return cost

def total_cost(weeks, number_of_textbooks):
        return renting_1(weeks) + renting_2(number_of_textbooks, weeks) + school_cost(weeks)

print total_cost(22, 4)

当我运行它时,我接受了这个

Traceback (most recent call last):
  File "python", line 22, in <module>
  File "python", line 20, in total_cost
TypeError: renting_1() takes exactly 2 arguments (1 given)

有人可以解释并修复代码,以便分析出错了吗?

5 个答案:

答案 0 :(得分:3)

从你得到的错误看来,一些参数对你的用例来说并不是强制性的。您可以删除这些参数,也可以为其他参数发送None或使用可选参数。

可以在最后添加可选参数,方法是为它们设置默认值,如下所示。

参考: http://www.diveintopython.net/power_of_introspection/optional_arguments.html

def renting_1(weeks, laptop=None):
    laptop = 5 * weeks
    if weeks > 10:
            laptop -= 120
    elif weeks > 5:
            laptop -= 50
    return laptop

def renting_2(number_of_textbooks, weeks, textbooks=None):
    textbooks = number_of_textbooks * 20 + (10 * weeks)
    if weeks >= 26:
            textbooks -= (5 * (weeks - 26))
    return textbooks

def school_cost(weeks, cost=None):
    cost = 200 * weeks
    return cost

def total_cost(weeks, number_of_textbooks):
    return renting_1(weeks) + renting_2(number_of_textbooks, weeks) + school_cost(weeks)

print total_cost(22, 4)

答案 1 :(得分:0)

正是它所说的“renting_1()只需要2个参数(给定1个)”

所以你构建了renting_1函数来接受2个参数,(笔记本电脑和周),但你只用一个参数renting_1(周)来调用它。您需要为笔记本电脑的函数调用参数添加另一个值。

答案 2 :(得分:0)

renting_1定义为接收2个参数laptopweeks

total_cost中使用它时,您可以这样称呼它:renting_1(weeks) 你传递了一个论点。

所有来电都有这个问题。有些事你不理解。

答案 3 :(得分:0)

您不需要在参数中定义返回值。

您尤其不应该覆盖通过计算其他值传递的参数

例如,您只需要def renting_1(weeks)

答案 4 :(得分:-1)

在代码的这一部分中,renting_1(laptop, weeks)需要2个参数,而您只提供了一个参数。

def total_cost(weeks, number_of_textbooks):
        return renting_1(weeks) + renting_2(number_of_textbooks, weeks) + school_cost(weeks)