可选参数 Python

tit*_*ako 4 python debugging arguments optional

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

该函数应采用三个参数:

  • 温度,浮动
  • 天气,字符串
  • is_celsius,一个布尔值

如果温度低于冰点(如果 is_celsius 为 False,则为 32,如果 is_celsius 为 True,则该函数应返回 True)或天气“下雪”。否则,它应该返回 False。

但是请注意, is_celsius 应该是一个可选参数。如果函数调用没有为 is_celsius 提供值,则假定它为 True。

我写了这个

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
Run Code Online (Sandbox Code Playgroud)

以及以下电话

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
Run Code Online (Sandbox Code Playgroud)

我越来越

None
None
True
Run Code Online (Sandbox Code Playgroud)

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

ala*_*ani 5

这不是使用有意义的情况**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
Run Code Online (Sandbox Code Playgroud)

但是,如果有充分的理由在字典中捕获可选参数(也许您还需要将其传递给您正在包装的函数),那么您可以使用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
Run Code Online (Sandbox Code Playgroud)