Making an argument as optional in Python function

Sometimes we need to make an argument as optional so that people using the function can choose to provide extra information only if they want to.

For example, say we want to expand get_user_name() in the previous topic to handle middle names as well.

Here is the python code to fulfill the the requirement above:


#!/usr/bin/python

# Give the middle_name argument an empty default value and ignore
# the argument unless the user provides a value,
# We set default value of middle_name to an empty string and 
# move it to the end of the list parameters

def get_user_name (first_name,last_name,middle_name=''):
    """ Return a full name"""
    if middle_name:
       full_name = first_name + ' ' + middle_name + ' ' +last_name
    else:
        full_name = first_name + ' ' +last_name
 
    return full_name.title()
 
my_user_name = get_user_name('Askari','Azikin')
my_completed_user_name = get_user_name('Askari','Azikin','Basa')
 
print(my_user_name)
print(my_completed_user_name)

Leave a Reply

Your email address will not be published. Required fields are marked *