Command Line and Variable Arguments in Python:

We will look at the command line arguments and variable arguments for functions in Python for Data Science.

Command line arguments:

Until now we have provided input in Python by either using raw_input() or input(). But we also have another method which uses command line arguments. We must provide the command line arguments before start of a script.

So, we can process the command line arguments in Python by either using ‘sys’ module or ‘argparse’ module.

Command Line and Variable Arguments in Python for Data Science - PST

We should remember the following about the above program:

  • The sys.argv will take command line arguments in the form of list.
  • The name of the file is the first element of the list.
  • Arguments will always come in the form of a string even if we input an integer. We have to use the int() function for the conversion of string to integer.

The command line arguments can be used for writing programs that perform frequently used tasks. Example: Factorial has to be found many times. We will keep this function in a file named factorial.py, and we will get the factorial by simply writing the command for obtaining factorial of a number.

Command Line and Variable Arguments in Python for Data Science - PST

Variable arguments:

args(*) and kwargs(**):

We use ‘args’ and ‘kwargs’ for getting arbitrary number of arguments in a function.

args will provide us with all function parameters in a list form, and kwargs provides all keyword arguments excluding the ones corresponding to formal parameter as dictionary.

Command Line and Variable Arguments in Python for Data Science - PST

We should observe that args is denoted by a single asterix and kwargs is denoted by a double asterix before the formal parameters in a function.

Command Line and Variable Arguments in Python for Data Science - PST

In case we are using both the args and kwargs in a functions, we should place the args parameters before the kwargs parameters.

So, to learn more about it in python for data science, you can check this and this as well.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.