Reputation: 4426
What should I pass to use the default value for "name"? I do not want to explicitly pass 'lisa' since it is the default argument and the user might not be aware. But if I pass an variable "name", I have to use a if else clause to pass nothing to the function in order to print"lisa".
def print_name(name='lisa'):
print name
if name != '':
print_name(name)
else:
print_name() # print lisa
Upvotes: 1
Views: 31
Reputation: 365747
What you probably want here is to make the function a bit more complicated:
def print_name(name=None):
if not name:
name='lisa'
print name
… so you can make calling it a lot simpler:
print_name(name)
That if not name:
will be true whenever name
is anything falsey—whether that's the default value of None
, or an empty string. That may not be exactly what you want—maybe you want to explicitly set the default value to ''
and check if name == '':
, for example—but it's usually a good first guess.
So:
>>> name = ''
>>> print_name(name)
lisa
>>> name = 'alis'
>>> print_name(name)
alis
… but you can still do this:
>>> print_name()
lisa
… which is presumably the reason you added a default value in the first place.
Upvotes: 3