Python3 Function Arguments

Python Function Arguments

1 . Function Arguments :

       def greet(name, msg):
             print("Hello {0}, {1} ".format(name, msg))

       #call a function with arguments
       greet("Satish", "good morning")

output: Hello Satish, good morning

       #suppose if we pass one argument
       greet("satish")

output:  ----------------------------------------------------------------------
              ---
              TypeError
              TypeError : greet( ) missing 1 required positional argument: 'msg'


Different Forms of Arguments :

       def greet(name, msg="good morning"):
             print("Hello {0} , {1}".format(name, msg))
   
       greet("Satish", "good night")

output:   Hello Satish , good night

       #with out msg argument
       greet("Satish")

 output:  Hello Satish , good morning

  Once we have a default argument , all the arguments to its right must also have default values.

   def  greet(msg="Good Morning", name)
  #will get a SyntaxError : non-default argument follows default argument

2 . Keyword Argument

    Kwargs allows you to pass keywords variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function

 Example:

       def greet(**kwargs):
             " " "
             This function greets to person with the provided messages
             if kwargs:
                  print("Hello {0}, {1}" .format(kwargs['name'], kwargs['msg']))

       greet(name="Satish", msg="Good Morning")

output: Hello Satish, Good Morning 

3. Arbitary Arguments

   Sometimes, we don't know in advance the number of arguments that will be pass into a function. Python allows us to handle this kind of situation through function call with arbitary number of arguments.

Example: 
  
       def greet(*names):
             """
             This function greets all persons in the names tuple
             """
             print(names)
             for name in names:
                   print("Hello {0}".format(name))

       greet("Ravi", "Raju", "Ram")

output:  ('Ravi', 'Raju', 'Ram')
               Hello Ravi
               Hello Raju
               Hello Ram









Comments

Popular posts from this blog

Python3 File Handling

Python3