Reputation: 45
A very easy Python code. I wish to obtain the following:
>>> 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'
This is my code. I want to ignore any cheese in my first sentence. How do i do that?
>>> 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')
This is my code. I want to ignore any cheese in my first sentence. How do i do that?
Upvotes: 0
Views: 167
Reputation: 178
Changing the default value from None
to ""
(empty string) should do the trick
Edit : Sorry late night and not thinking clearly. Split your print line into an if check. If you cheese is "" print line without the cheese bit and else print the line you have now.
Sorry for not providing code example, posting from my phone, shouldn't do that I suppose
Upvotes: 1
Reputation: 4318
Are you looking for this
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
If cheese is not passed, it gets the default value None from function definition. Based on that, you can decide print sentence with cheese.
Upvotes: 0
Reputation: 4624
one easy way is:
def sandwich(bread, meat='turkey', cheese=None):
print bread,"bread sandwich with",meat,
if cheese:
print "and",cheese,"cheese"
Upvotes: 0