Python Classroom Series – 16/Sept/2020

Python argparse module for command line

  • Refer Here for docs
  • As discussed in the class try building the command line calculator
python --operation <add/sub/mul/div/modulous>
  • Code implementation so far is

#!/usr/bin/env python3

import argparse

def parse_arguments():
    This method will parse the arguments
    # Created an parser
    parser = argparse.ArgumentParser()
    parser.add_argument('-v', '--value', type=int, action='append', dest='numbers', help='Enter numbers')
    parser.add_argument('-o', '--operation', required=True, choices=['add', 'mul'])
    # # optional boolean argument
    # parser.add_argument('-o', '--output', action='store_true', help="Show Output")
    # # required argument
    # parser.add_argument('-n', '--name', required=True, help="Enter your name")
    # # specify type of input
    # parser.add_argument('-a', '--age', type=int, required=True, help="Enter your age")
    # # default value to the optional argument
    # parser.add_argument('-g', '--gender', default='Not Specified', help='Enter your gender')
    args = parser.parse_args()
    result = 0
    for number in args.numbers:
        if args.operation == 'add':
            result = result + number
        elif args.operation == 'mul':
            if result == 0:
                result = 1
            result = result * number


if __name__ == "__main__":


  • Please watch previous 3 classes of Linux-Regex Refer Here

Interesting Functions in Python

  • Inner functions: An inner function can be useful when performing complex task more than once within a function.
def outer_function(arg1, arg2):
    def inner_function(arg3, arg4):
        return arg3 * arg4
    return inner_function(arg1, arg2)

if __name__ == "__main__":
    print(outer_function(4, 6))

  • Closures
  • Lambda
  • Generators
  • Generator Comprehensions
  • Decorators

Leave a Comment

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

About learningthoughtsadmin