This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Problems with sys.argv

But…. my users are very naughty!

They just keep crashing my calculator with weird inputs! 😭

$ python3 calculator.py 3 5
$ python3 calculator.py
$ python3 calculator.py 3+5
$ python3 calculator.py add 4
$ python3 calculator.py 2
$ python3 calculator.py 5 2 and
$ python3 calculator.py 1 infinity
$ python3 calculator.py 4 8 6
$ python3 calculator.py a - b
$ python3 calculator.py not another lockdown
$ python3 calculator.py 1 2 3 4 5 6 7 8
$ python3 calculator.py girls just wanna have fun!!!

Of course, you are now masters of exception handling, so let’s use your new found skills to the best of your abilities!

import sys

def calculate(x, y, operation):
    if operation == "add":
        return x + y
    elif operation == "sub":
        return x - y
    elif operation == "mul":
        return x * y
    elif operation == "div":
        return x / y
    else:
        raise Exception(f"Invalid operation {operation}. We only accept add, sub, mul, and div.")

if __name__ == "__main__":
    if len(sys.argv) != 4:
        raise Exception("You should provide exactly 3 arguments: number number operation")

    try:
        x = int(sys.argv[1])
        y = int(sys.argv[2])
    except ValueError:
        raise Exception("The first two arguments must be integers")

    operation = sys.argv[3]
  
    print(calculate(x, y, operation))

Phew… I think we covered everything that could go wrong. I hope. Did I?

But why does it feel so tedious and painful?! There must be a better way to do this! Arrghhh!!