Python:TypeError:只需要1个参数(给定2个)

Joh*_*ohn 3 python

我目前正在使用singpath.com练习我的python,但是我遇到了一个问题:

预期的结果是:

>>>CurryPuff(3) 
3.60 
>>>CurryPuff(3,'Fish') 
4.2
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的:

def CurryPuff(x,typePuff):

   if(typePuff==''):

      return x*1.2

   if(typePuff=='Fish'):

      return x*1.4
Run Code Online (Sandbox Code Playgroud)

但它给了我这个错误:

TypeError: CurryPuff() takes exactly 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)

我曾尝试谷歌搜索,但我不是很确定使用的关键词是什么,所以希望能从这里获得帮助.

谢谢.

Raf*_*ler 16

如果期望为2,则不能使用1参数调用函数CurryPuff().但是,您可以定义在未传递参数时使用的默认参数:

def CurryPuff(x, typePuff=None):
    if typePuff is None:
       # and so on...
Run Code Online (Sandbox Code Playgroud)

您可以使用任何参数的任何值执行此操作.如果定义了默认值,则只能省略参数.

  • +1,但您可能想要添加您需要在任何关键字参数(具有默认值的参数)之前放置位置参数(没有默认值的参数).`def CurryPuff(typePuff = None,x):`将无效. (2认同)