#-------------------------------------------------------------------------------------# @ File: Calculator. py# @ project: blog# @ time : 2018/3/17 20:14# @ Author: Liu yang# @ blog: www.liuyang1.club# @ email: [email protected]#--------------------------------- ---------------------------------------------------# Encoding Format #-*-coding:utf-8-*-# python version # #!/usr/bin/python3import Reexprs = ' # expression sum = 0 # result flag = ' new ' # Calculate flag bit def License (): Print ("********** Console calculator ******** \n supports +-x/operations, exponential operations (^), \n supports long expression input with parentheses \n Welcome to the blog: www.liuyang1.club \ n CopyRight (c) 2018 ********\n ") def Bracketunbalancecheck (str_in): num = 0 for i in str_in: if i = = ' (': num + = 1 elif i = = ') ': num-= 1 if num! = 0: # brackets unbalanced print ("Error: Input Parentheses unbalanced, please reenter \ n ") return 1 Else: # Bracket Balance return-1def Charerrorcheck (str_in): If Re.findall (R ' [&a-za -z<>,[email protected]#$% ";:] ', str_in): # Regular expression checks the legitimacy of the input string print (' ERROR: expression contains illegal characters, please reenter \ n ') return 1 else:return-1def input Expression (): Global Exprs While Not (Charerrorcheck (EXPRS) = = 1 and Bracketunbalancecheck (EXPRS) = =-1): # until you get a The valid expression Exprs = input ("Continue input expression: \ n") m = Re.match (R ' ^[\^/\*+\-\\]\w* ', Exprs) # matches whether the first character of the input string is an operator, determines the continuation operation or begins a new calculation If M:return ' Continue ' else:return ' new ' Def Compute (flag): Global EXPRS global Sum Exprs = Exprs.replace (' ^ ', ' * * ') # replaces ^ with * if flag = = ' Continue ': Exprs = str (sum) + Exprs try:sum = eval (E XPRS) Print ("Computed:", Exprs) print (Exprs, "=" + str (SUM)) except Syntaxerror:print ("Error: A syntax error occurred while continuing the calculation , the program returns \ n ") except Zerodivisionerror:print (" error: Divisor cannot be 0, program returns \ n ") def Main (): Global EXPRS, Flag License () W Hile True:exprs = input ("Input expression:") flag = Inputexpression () Compute (flag) if __name__ = = ' __main__ ': Main ()
[Python Study Notes] Calculator