Introduction to argparse

Agrparse makes it easy to write user-friendly command line interfaces. This module automatically generates help and usage messages  when users passed the invalid arguments to program.

To understand the whole concept of argparse module we will go through an example.

Let’s define a function which calculates the total marks a student got in all subjects.

The whole code is like this -:

import argparse
import sys

def marks(args):
    if args.type_res == 'Total':
        return args.chem+args.maths+args.phy
    if type_res == 'Average':
        return (args.chem+args.maths+args.phy)/3

def execute_main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--chem', type=float, default=1.0,
                            help='What is the marks secured in chemistry?')
    parser.add_argument('--maths', type=float, default=1.0,
                            help='What is the marks secured in maths?')
    parser.add_argument('--phy', type=str, default=1.0,
                            help='What is the marks secured in physics?')
    parser.add_argument('--type_res', type=str, default='Total',
                            help='What type of result? Can choose total or average')

    args = parser.parse_args()

if __name__ == '__main__':

If you run this program normally in idle it will show the output as -:

RESTART: C:\Python\Python36\ = 3.0. 

It is giving three as output because of default parameters.

In command line you can run these commands and get the output