2017-12-03 213 views
-1

我想申请什么我已经了解的功能和参数,所以我想出了可以计算的学费(纯属假设)我的函数和参数代码有什么问题?

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) 

有人可以解释,也许修复代码,所以我可以分析什么是错的?

+1

为什么'laptop'的功能位置参数'renting_1'?它不应该在那里吗?因为你正在函数中重新定义'laptop'。 – abccd

+2

你在这里给出了一个参数......'renting_1(weeks)'阅读错误。 –

+0

对于您的函数'renting_1','renting_2'和'school_cost',您添加了第一个参数,该参数不应该在那里。从参数中分别删除'laptop','textbooks'和'cost'。这可能是一个错字,或者你不太理解论证如何工作。还要阅读错误信息,那个很清楚。 –

回答

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

我不知道OPs使用什么情况是。所以,加上这个以防万一。 –

+1

即使通过了一个值,它也会被覆盖 –

-1

在代码中的这一部分,renting_1(laptop, weeks)需要两个参数,你只给一个。

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

这解释了问题,而不是解决方案 –

0

正是它说“renting_1()到底需要2个参数(1给出)”

所以你建的renting_1函数接受2个参数,(笔记本&周),但你只把它称为租用1(周)的一个论据。您需要为笔记本电脑的函数调用参数添加另一个值。

0

renting_1被定义为接收2个参数laptopweeks

当您在total_cost中使用它时,可以这样称呼它:renting_1(weeks) 您传递了一个参数。

所有调用都有此问题。有些事你不了解。

0

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

您尤应不会覆盖与计算其它值

例如传入的参数,def renting_1(weeks)是所有你需要