Friday 4 December 2015

Python: functions: Default Argument Values

In Python, you can pass default values to function arguments.

def welcomeMessage(name='user', message='Hello'):
         print(message, name)

You can call above function in following ways.

welcomeMessage() : prints ‘Hello user‘
welcomeMessage('Krishna') : prints ‘Hello Krishna‘
welcomeMessage('Krishna', "Welcome") : prints ‘Welcome krishna‘.


test.py
def welcomeMessage(name='user', message='Hello'):
 print(message, name)


welcomeMessage()
welcomeMessage('Krishna')
welcomeMessage('Krishna', "Welcome")

$ python3 test.py
Hello user
Hello Krishna
Welcome krishna

Note:
Default value is evaluated only once. So be cautious, while using mutable objects like lists, dictionary etc., For example, following function accumulates the result in subsequent calls.

test.py
def getEvenNumbers(limit, result=[]):
 i=2
 while(i < limit):
  result.append(i)
  i+=2
 
 return result
 
print(getEvenNumbers(4))
print(getEvenNumbers(8))
print(getEvenNumbers(12))


$ python3 test.py
[2]
[2, 2, 4, 6]
[2, 2, 4, 6, 2, 4, 6, 8, 10]

If you don’t want the default to be shared between subsequent calls, you can write the function like below instead:

def getEvenNumbers(limit, result=None):
 if result is None:
  result=[]
 
 i=2
 while(i < limit):
  result.append(i)
  i+=2
 
 return result
 
print(getEvenNumbers(4))
print(getEvenNumbers(8))
print(getEvenNumbers(12))


$ python3 test.py
[2]
[2, 4, 6]
[2, 4, 6, 8, 10]




Previous                                                 Next                                                 Home

No comments:

Post a Comment