Pybites Logo

Create a simple calculator that receives command line arguments

Level: Intermediate (score: 3)

In this Bite you write a simple calculator that can perform additions (add), subtractions (sub), multiplications (mul) and divisions (div).

You will use argparse to interface with the program. You will make it work like this:

$ python calculator.py -h
usage: calculator.py [-h] [-a ADD [ADD ...]] [-s SUB [SUB ...]]
                     [-m MUL [MUL ...]] [-d DIV [DIV ...]]

A simple calculator

optional arguments:
  -h, --help            show this help message and exit
  -a ADD [ADD ...], --add ADD [ADD ...]
                        Sums numbers
  -s SUB [SUB ...], --sub SUB [SUB ...]
                        Subtracts numbers
  -m MUL [MUL ...], --mul MUL [MUL ...]
                        Multiplies numbers
  -d DIV [DIV ...], --div DIV [DIV ...]
                        Divides numbers


$ python calculator.py --add 1 2 3
6.0
$ python calculator.py --sub 10 6 2
2.0
$ python calculator.py --mul 3 3 3
27.0
$ python calculator.py --div 8 5 7
0.23

See also the TESTS tab for more info. Good luck and have fun ... argparse is a good skill to have!

If new to argparse you might want to check out Bite 56 first. For a more advanced Bite try 58.