可选参数 Python

optional argument Python

必须编写一些代码来定义将使用两个或三个参数的函数。

该函数应采用三个参数:

函数应该return如果温度低于 冻结(如果 is_celsius 为 False,则为 32,如果 is_celsius 为 False,则为 0 真)或天气是否“下雪”。否则,它应该 return 错误。

但是请注意,is_celsius 应该是可选的 争论。如果函数调用没有为 is_celsius,假定为真。

这是我写的

def snowed_in(temperature, weather, **cels):
    if weather =="snowy":
        return True
    elif weather=="sunny":
        if 'is_celsius = False' in cels:
            if temperature<32:
                return True
    elif 'is_celsius = True' in cels:
        if temperature<0:
            print ('ad')    
            return True
    elif 'is_celsius = True' not in cels:
        if temperature<0:
            return True
    else:
        return False

以及以下调用

print(snowed_in(15, "sunny")) #Should print False
print(snowed_in(15, "sunny",is_celsius = False)) #Should print True
print(snowed_in(15, "snowy",is_celsius = True)) #Should print True

我得到

None
None
True

有人可以帮我找出我的代码有什么问题吗?

在这种情况下使用 **kwargs 是没有意义的 - 通常用于包装函数。

你应该简单地做这样的事情来明确声明 is_celsius 作为可选参数:

def snowed_in(temperature, weather, is_celsius=True):
    if weather == "snowy":
        return True
    elif is_celsius:
        return temperature < 0
    else:
        return temperature < 32

但是,如果有充分的理由在字典中捕获可选参数(也许您还需要将其传递给您正在包装的函数),那么您可以使用 get 提取相关参数使用任何默认值(否则它将默认为 None):

def snowed_in(temperature, weather, **kwargs):
    if weather == "snowy":
        return True
    elif kwargs.get('is_celsius', True):
        return temperature < 0
    else:
        return temperature < 32

这里有一些东西,所以让我 post 编辑您的代码并与您一起逐步完成更改 :)

def snowed_in(temperature, weather, cels=True):
    if weather =="snowy":
        return True
    elif weather=="sunny":
        if not cels:
            if temperature<32:
                return True
    elif cels:
        if temperature<0:
            print ('ad')    
            return True
    else:
        return False

布尔表达式

您将 is_celsius 作为布尔值输入,但将其计算为一个有点奇怪的字符串。

与其尝试匹配特定字符串,即 'is_celsius = True' in cels:,不如检查布尔值 'cels' 的状态,即 if cels:

默认参数

如果函数调用没有为 is_celsius 提供值,则假定它为 True。... python 函数参数可以有默认值.

因此,对于您想要的行为,使用 cels=True**cels 更可取。

现在,如果函数调用中未指定 celscels=True 将被传递给函数。

语法

如果您是 Python check out PEP8 的新手。这里的要点是你应该尽量不要在函数参数中的变量名和它的值之间有空格,即 cels=True 而不是 cels = True.

缩进

我假设这是您复制粘贴代码的产物。但!请注意,缩进在 python 中非常重要。请注意您的代码与我上面的示例之间的区别......如果您将代码复制粘贴到堆栈溢出/其他地方,确保您的代码具有正确的缩进是一种很好的做法。让其他人更容易阅读!

祝你好运!