Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python关键字参数额外单词_Python - Fatal编程技术网

Python关键字参数额外单词

Python关键字参数额外单词,python,Python,一个非常简单的Python代码。我希望获得以下资料: >>> sandwich('wheat') 'wheat bread sandwich with turkey' >>> sandwich('white', meat='ham', cheese='American') 'white bread sandwich with ham and American cheese' >>> sandwich('white', cheese='Am

一个非常简单的Python代码。我希望获得以下资料:

>>> sandwich('wheat')
 'wheat bread sandwich with turkey'
>>> sandwich('white', meat='ham', cheese='American')
 'white bread sandwich with ham and American cheese'
>>> sandwich('white', cheese='American', meat='ham')
'white bread sandwich with ham and American cheese'
>>> sandwich('rye','ham','Swiss')
 'rye bread sandwich with ham and Swiss cheese'
>>> sandwich('white', cheese='provolone')
 'white bread sandwich with turkey and provolone cheese'
这是我的密码。我想在第一句话中忽略任何奶酪。我该怎么做

>>> def sandwich(bread, meat='turkey', cheese=None):
>>>     print bread,"bread sandwich with",meat,"and",cheese,"cheese"


>>> sandwich('wheat')
>>> sandwich('white', meat='ham', cheese='American')
>>> sandwich('white', cheese='American', meat='ham')
>>> sandwich('rye','ham','Swiss')
>>> sandwich('white', cheese='provolone')

这是我的密码。我想在第一句话中忽略任何奶酪。我该怎么做?

将默认值从
None
更改为
(空字符串)应该可以做到这一点

>>> def sandwich(bread, meat='turkey', cheese=None):
>>>     print bread,"bread sandwich with",meat,"and",cheese,"cheese"


>>> sandwich('wheat')
>>> sandwich('white', meat='ham', cheese='American')
>>> sandwich('white', cheese='American', meat='ham')
>>> sandwich('rye','ham','Swiss')
>>> sandwich('white', cheese='provolone')
编辑: 抱歉,我昨晚没想清楚。将打印行拆分为if检查。如果您的cheese为“”,则打印不带cheese位的行,否则打印您现在的行

很抱歉没有提供代码示例,从我的手机发帖,不应该这样做,我想一个简单的方法是:

def sandwich(bread, meat='turkey', cheese=None):
    print bread,"bread sandwich with",meat,      
    if cheese:
        print "and",cheese,"cheese"

你在找这个吗

def sandwich(bread, meat='turkey', cheese=None):
    if cheese:
        print bread,"bread sandwich with",meat,"and",cheese,"cheese"
    else:
        print bread,"bread sandwich with",meat
如果未传递cheese,则从函数定义中获取默认值None。基于此,您可以决定使用奶酪打印句子。

如果没有奶酪,我想删除“and cheese”。它仍然出现“…和奶酪。”