Python关键字参数额外的单词

时间:2014-03-22 04:04:24

标签: 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='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')

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

3 个答案:

答案 0 :(得分:1)

将默认值从None更改为""(空字符串)应该可以解决问题

编辑: 对不起深夜,没有想清楚。将打印行拆分为if检查。如果你的奶酪是“”打印线没有奶酪位,否则打印你现在的线。

很抱歉没有提供代码示例,从我的手机发布,我想不应该这样做

答案 1 :(得分:0)

一个简单的方法是:

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

答案 2 :(得分:0)

你在找这个吗?

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。基于此,您可以决定用奶酪打印句子。