• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

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

python 来源:Khan Niekamp 3次浏览

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

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) 

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


===========解决方案如下:

从你得到的错误来看,你的用例似乎有些参数不是强制性的。您可以删除这些参数,也可以发送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) 

版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)