avatar Bite 57. Create a simple calculator that receives command line arguments

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.

Login and get coding
go back Intermediate level
Bitecoin 3X

182 out of 188 users completed this Bite.
Will you be Pythonista #183 to crack this Bite?
Resolution time: ~70 min. (avg. submissions of 5-240 min.)
Pythonistas rate this Bite 6.75 on a 1-10 difficulty scale.
» Up for a challenge? 💪

Focus on this Bite hiding sidebars, turn on Focus Mode.

Ask for Help