Auto AdSense

Saturday, 24 January 2015

Python Programs - Function Arguments






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

    Keyword arguments

    Default arguments

    Variable-length arguments
  • Required arguments:
    To call the function printme() you definitely need to pass one argument otherwise it would give a syntax error as follows:

    #!/usr/bin/python

    # Function definition is here
    def printme( str ):
       "This prints a passed string into this function"
       print str;
       return;

    # Now you can call printme function
    printme();
  • Output
    Traceback (most recent call last):
      File "test.py", line 11, in < module >
       printme();
    TypeError: printme() takes exactly 1 argument (0 given)
  • Keyword arguments:
    This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.
    You can also make keyword calls to the printme() function in the following ways:

    #!/usr/bin/python

    # Function definition is here
    def printme( str ):
       "This prints a passed string into this function"
      print str;
      return;

    # Now you can call printme function
    printme( str = "My string");
  • Output
    My string
  • Default arguments:
    #!/usr/bin/python

    # Function definition is here
    def printinfo( name, age = 35 ):
     "This prints a passed info into this function"
     print "Name: ", name;
     print "Age ", age;
     return;

    # Now you can call printinfo function
    printinfo( age=50, name="miki" );
    printinfo( name="miki" );
  • Output
    Name: miki
    Age 50
    Name: miki
    Age 35
  • Variable-length arguments:
    Syntax:
    def functionname([formal_args,] *var_args_tuple ):
     "function_docstring"
     function_suite
     return [expression]

    Example:
    #!/usr/bin/python

    # Function definition is here
    def printinfo( arg1, *vartuple ):
      "This prints a variable passed arguments"
      print "Output is: "
      print arg1
      for var in vartuple:
        print var
    return;

    # Now you can call printinfo function
    printinfo( 10 );
    printinfo( 70, 60, 50 );
  • Output
    Output is:
    10
    Output is:
    70
    60
    50

No comments:

Post a Comment