# Kyle Saburao, October 09, 2016, 7:06 pm
# Notes: Index handling is janky and there's probably a better way

file = 'text.txt'
commands = ('add', 'subtract', 'divide', 'multiply')

with open(file) as objectItem:
    lines = objectItem.readlines()
    lines = [x.strip('\n').lower() for x in lines]

for num, content in enumerate(lines):
    if content in commands:
        try:
            if 'result:' in lines[num + 3 ]:
                lines[num + 3] = 'result: '
                n1 = int(lines[num + 1])
                n2 = int(lines[num + 2])
                if content == 'add':
                    lines[num + 3] += str(n1 + n2)
                elif content == 'subtract':
                    lines[num + 3] += str(n1 - n2)
                elif content == 'divide':
                    if n2 != 0:
                        lines[num + 3] += str(n1 / n2)
                    else:
                        lines[num + 3] = 'result: Cannot divide by zero'
                elif content == 'multiply':
                    lines[num + 3] += str(n1 * n2)
        except IndexError:
            print('No numbers found past "{}"'.format(str(lines[num])))

with open(file, 'w') as objectItem:
    objectItem.write("\n".join(lines))
