#!/usr/bin/python3 import sys def parse(calculation): global operator,operand1,operand2 tokenIndex = 0 tokens = ["","",""] i=0 numberBeginning = True while i < len(calculation): print("Token index: ",tokenIndex,"character[",i,": ]",calculation[i]) # spaces are simply skipped if calculation[i] == " ": print("space") i+=1 # A number consists of characters between 0 and 9 or the decimal point and possibly a preceeding minus sign elif numberBeginning and calculation[i] == '-': tokens[tokenIndex] = '-' numberBeginning = False i+=1 elif calculation[i] >= '0' and calculation[i] <= '9': print("number: ",calculation[i]) tokens[tokenIndex]=tokens[tokenIndex]+calculation[i] numberBeginning = False i += 1 # a decimal point is also allowed elif calculation[i] == '.': print("dot") # check that the decimal point was not already given, no 2 decimal points allowed if tokens[tokenIndex].find('.') == -1: tokens[tokenIndex]= tokens[tokenIndex]+calculation[i] i += 1 numberBeginning = False else: return False # It can still be an operator. In this case the first operand must be non null elif tokenIndex == 0 and not tokens[0] == "": if calculation[i] == '+' or calculation[i] == '-' or calculation[i] == '*' or calculation[i] == '/' : print("Found operator: ",calculation[i]) # save the operator and continue parsing the second operand tokens[1]=tokens[1]+calculation[i] tokenIndex += 2 numberBeginning = True i += 1 else: return False else: return False # print("First operand: ",tokens[0]) # print("Second operand: ",tokens[2]) # print("Operator: ",tokens[1]) operator = tokens[1] #if the operand contains a decimal point it must also contain at least 1 digit if len(tokens[0]) == 0 or len(tokens[2]) == 0: return False if tokens[0].find('.') != -1 and len(tokens[0]) == 1: return False if tokens[2].find('.') != -1 and len(tokens[2]) == 1: return False operand1 = float(tokens[0]) operand2 = float(tokens[2]) return True def plus(): print(operand1,' + ',operand2,' = ',operand1+operand2) def minus(): print(operand1,' - ',operand2,' = ',operand1-operand2) def multiply(): print(operand1,' * ',operand2,' = ',operand1*operand2) def divide(): try: print(operand1,' / ',operand2,' = ',operand1/operand2) except ZeroDivisionError: print('Cannot divide by zero') operations= {'+' : plus, '-' : minus, '*' : multiply, '/' : divide,} global operator,operand1,operand2 while True: print ('Enter the calculation to be performed in the form: "operand1 operator operand2"') print ('Example: "5.3 + 4.2" or "1.4 * 7.9"'); print ('Operation: ',end='') # if the input is empty just try again calculation = input() if calculation=="": continue # print(calculation) if parse(calculation): # print("String ok"); operations[operator]() sys.exit() else: print("Bad operation input: ",calculation)