Function Arguments

Function Arguments

Example 1 - Positive Scenario

# Function to Welcome User with greeting message - 2 Arguements
def welcomeUser(name,message):
    """ 
    This function welcome's the user with greeting message
    """
    print("Dear {0} , {1}".format(name, message))

# Calling the function
welcomeUser("Kiran","Have a nice day")

Output:
Dear Kiran , Have a nice day

Example 2 - Negative Scenario

# For the above function if we pass one argument
welcomeUser("Kiran")

Output:
---------------------------------------------------------------------------
TypeError: Traceback (most recent call last)
<ipython-input-10-eff0d6eef4db> in <module>()
      1 # For the above function if we pass one argument
      2 
----> 3 welcomeUser("Kiran")

TypeError: welcomeUser() missing 1 required positional argument: 'message'

Different Forms of Function Arguments

You can call a function by using the following types of formal arguments:

  1. Default arguments
  2. Keyword arguments
  3. Arbitrary Arguments

1. Default Arguments

  • A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.
  • To specify default values of argument, you just need to assign a value using assignment operator '='.
  • It is also called positional arguments.

  • Example 3

    # Function to Welcome User with greeting message by providing default message
    def welcomeUser(name , message="Have a nice day"):
        """ 
        This function welcome's the user with greeting message
        """
        print("Dear {0} , {1}".format(name, message))
    
    # Calling the function
    welcomeUser("Kiran")
    
    Output:
    Dear Kiran , Have a nice day
    

    Example 4

    # Reusing the same function with different values
    welcomeUser("Muthu","Good morning")
    welcomeUser("Raghu","Good evening")
    welcomeUser("Karthik")
    
    Output:
    Dear Muthu , Good morning
    Dear Raghu , Good evening
    Dear Karthik , Have a nice day
    

    Note: Default Arguments

  • Any number of arguments in a function can have a default value.
  • Once we have a default argument, all the arguments to its right must also have default values.
  • Non-default arguments cannot follow default arguments.

  • Example 5

    # Function to Welcome User with greeting message by providing default message
    def welcomeUser(message="Have a nice day", name):
        """ 
        This function welcome's the user with greeting message
        """
        print("Dear {0} , {1}".format(name, message))
    
    # Calling the function
    welcomeUser("Good day","Kiran")
    
    Output:
    File "<ipython-input-19-f0a65d76eadb>", line 2
        def welcomeUser(message="Have a nice day", name):
                       ^
    SyntaxError: non-default argument follows default argument
    

    2. Keyword Arguments

  • Keyword arguments allows you to pass each arguments using 'name value' pairs Eg: name="Binish".
  • When we call functions using keyword arguments, the order (position) of the arguments can be changed.
  • It is fixed arguments. ie the number of arguments mentioned in functions are fixed.

  • Example 6

  • '**kwargs' can be used to used to send multiple arguments using single keyword ie variable-length argument list.
  • It is similar to Dictionary concept.
  • # Function to display the employee details using '**kwargs'
    def employeeDetails(**user):
        """ 
        This function used to display the employee details
        """
        print("Name: ", user['name'])
        print("Age: ",  user['age'])
        print("Company: ", user["company"])
        
    # Calling the function
    employeeDetails(name="Binish",age="30",company="XYZ")
    
    Output:
    Name:  Binish
    Age:  30
    Company:  XYZ
    

    Example 7

    # Function to display the employee details by changing the position of arguments
    def employeeDetails(**user):
        """ 
        This function used to display the employee details
        """
        print("Name: ", user['name'])
        print("Age: ",  user['age'])
        print("Company: ", user["company"])
        
    # Calling the function
    employeeDetails(company="XYZ",age="30",name="Binish")
    
    Output:
    Name:  Binish
    Age:  30
    Company:  XYZ
    

    Example 8

    # Function to display the employee details in alternative way
    def employeeDetails(name, age, company):
        """ 
        This function used to display the employee details
        """
        print("Name: ", name)
        print("Age: ", age)
        print("Company: ", company)
        
    # Calling the function
    employeeDetails(name="Binish",age="30",company="XYZ")
    
    Output:
    Name:  Binish
    Age:  30
    Company:  XYZ
    

    Mixing Positional and Keyword Arguments

    It is possible to mix positional arguments and Keyword arguments, but for this positional argument must appear before any Keyword arguments

    #Sample Code
    employeeDetails("Binish",age="30",company="XYZ") # Valid 
    employeeDetails("Binish",age="30","XYZ") # Invalid 
    
    SyntaxError: non-keyword arg after keyword arg

    3. Arbitrary Arguments

  • When the nummber of arguments passed into a function is dynamic, ie we do not know in advance the number of arguments, then it can be handled using Arbitrary Arugments.
  • In the function definition we use an asterisk (*) before the parameter name to denote it ie '*args'.

  • Example 9:

    # Function to welcome all the user with greeting message 
    def welcomeUser(*names):
        """ 
        This function welcome all the user with greeting message 
        """
        print("The value entered by user",names)
        
        for name in names:
            print("Dear "+ str(name) +", Welcome to Python Tutorials")
    
    # Calling the function
    welcomeUser("Binish","Hari","Karthik","Raghul") 
    
    # Note: Here values passed as Tuples - We can do any manipulation from these tuples
    
    Output:
    The value entered by user ('Binish', 'Hari', 'Karthik', 'Raghul')
    Dear Binish, Welcome to Python Tutorials
    Dear Hari, Welcome to Python Tutorials
    Dear Karthik, Welcome to Python Tutorials
    Dear Raghul, Welcome to Python Tutorials