一个非常简单的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')这是我的密码。我想在我的第一句话中忽略任何奶酪。我该怎么做?
发布于 2014-03-22 04:10:44
你在找这个吗?
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如果不传递奶酪,则从函数定义中获得默认值None。在此基础上,你可以用奶酪决定打印句子。
发布于 2014-03-22 04:10:31
将默认值从None更改为"" (空字符串)就可以了
编辑:抱歉,深夜没有想清楚。将打印行拆分为if检查。如果你的奶酪是"“打印线没有奶酪位,否则打印的线条,你现在有。
对不起,没有提供代码示例,在我的手机上发帖,我想不应该这样做。
发布于 2014-03-22 04:10:41
一个简单的方法是:
def sandwich(bread, meat='turkey', cheese=None):
print bread,"bread sandwich with",meat,
if cheese:
print "and",cheese,"cheese"https://stackoverflow.com/questions/22573307
复制相似问题