Python:类型错误:正好需要 1 个参数(给出 2 个)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4743673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:18:49  来源:igfitidea点击:

Python: TypeError: takes exactly 1 argument (2 given)

python

提问by John

I'm currently using singpath.com to practice my python, but I face an issue with a problem:

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

The expected result is:

预期的结果是:

>>>CurryPuff(3) 
3.60 
>>>CurryPuff(3,'Fish') 
4.2

This is something I tried:

这是我尝试过的:

def CurryPuff(x,typePuff):

   if(typePuff==''):

      return x*1.2

   if(typePuff=='Fish'):

      return x*1.4

But it give me this error:

但它给了我这个错误:

TypeError: CurryPuff() takes exactly 2 arguments (1 given)

I had try googling on this but I'm not really very sure what is the key word to use, so hopefully can get help from here.

我曾尝试使用谷歌搜索,但我不太确定要使用的关键字是什么,所以希望能从这里得到帮助。

Thanks.

谢谢。

回答by Rafe Kettler

You can't call a function with 1 argument if it expects 2, as CurryPuff()does. However, you can define a default argument that is used if no argument is passed:

如果需要 2 个参数,则不能调用具有 1 个参数的函数,就像CurryPuff()那样。但是,您可以定义一个默认参数,如果没有传递参数,则使用该参数:

def CurryPuff(x, typePuff=None):
    if typePuff is None:
       # and so on...

You can do this with any value for any argument. You may only omit arguments if a default value is defined.

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