Exercises

Modify the scripts such that these additional features are also implemented.

  • If the output is of float data type, apply .2f precision by default. This should be overridden if a value is passed along with -f option. Also, add a new option -F to turn off the default .2f precision.

    $ pc '4 / 3'
    1.33
    
    $ pc -f3 '22 / 7'
    3.143
    
    $ pc -F '22 / 7'
    3.142857142857143
    
    # if output isn't float, .2f shouldn't be applied
    $ pc '12 ** 12'
    8916100448256
    
  • Use math module to allow mathematical methods and constants like sin, pi, etc.

    $ pc 'sin(radians(90))'
    1.00
    
    $ pc 'pi * 2'
    6.283185307179586
    
    $ pc 'factorial(5)'
    120
    
  • If the input expression has a sequence of numbers followed by ! character, replace such a sequence with the factorial value. Assume that input will not have ! applied to negative or floating-point numbers. Or, you can issue an error if such numbers are detected.

    $ pc '2 + 5!'
    122
    
  • Go through docs.python: ArgumentParser and experiment with parameters like description, epilog, etc.

Further Reading

Python has a rich ecosystem in addition to the impressive standard library. You can find plenty of modules to choose for common tasks, including alternatives for standard modules. Check out these projects for CLI related applications.

  • click — Python package for creating beautiful command line interfaces in a composable way with as little code as necessary
  • Gooey — turn Python command line program into a full GUI application
  • CLI Guidelines — an opinionated guide to help you write better CLI programs