本文主要是实现:计算器的应用,本人历经三天,费了九牛二虎之力,希望大家多多捧场,还有很多功能不完善,正在更新中·····
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # author by lh 4 5 import re 6 7 8 # 替换空格,++,--等符号 9 def rep(s): 10 s = s.replace(‘ ‘, ‘‘) 11 s = s.replace(‘++‘, ‘+‘) 12 s = s.replace(‘+-‘, ‘-‘) 13 s = s.replace(‘--‘, ‘+‘) 14 return s 15 16 17 # 检查是否合法 18 def checkout(s): 19 flag = True 20 if re.findall(‘[a-zA-Z]‘, s): 21 print(‘您可能输入了字母或特殊字符,请重新输入!‘) 22 flag = False 23 return flag 24 25 # 乘除运算 26 def mul_div(s): 27 while re.search(‘\d+\.?\d*[*/]-?\d+\.?\d*‘, s): # 条件满足时,做乘除 28 ret = re.search(‘\d+\.?\d*[*/]-?\d+\.?\d*‘, s).group() # 取出乘除表达式 29 x, y = re.split(‘[*/]‘, ret) # 取出计算的值 30 if ‘*‘ in ret: 31 mul = float(x) * float(y) 32 elif ‘/‘ in ret: 33 mul = float(x) / float(y) 34 s = s.replace(ret, str(mul)) # 计算结果代替旧的表达式 35 return s 36 37 # 加减运算 38 def add_minus(s): 39 while re.search(‘\d+\.?\d*[+-]\d+\.?\d*‘, s): 40 ret = re.search(‘\d+\.?\d*[+-]\d+\.?\d*‘, s).group() 41 x, y = re.split(‘[+-]‘, ret) 42 if ‘+‘ in ret: 43 add = float(x) + float(y) 44 elif ‘-‘ in ret: 45 add = float(x) - float(y) 46 s = s.replace(ret, str(add)) 47 s = rep(s) 48 return s 49 50 51 str1 = input(‘请输入您要计算的表达式:‘) 52 str1 = rep(str1) 53 if checkout(str1): 54 while re.search(‘\(‘, str1): # 找到最后一个括号 55 a = re.search(‘\([^()]+\)‘, str1).group() # 找到最后一个括号中的表达式 56 n = re.sub(‘[()]‘, ‘‘, a) # 去括号 57 a1 = mul_div(n) # 计算乘除 58 str1 = rep(str1) 59 res = add_minus(a1) # 计算加减 60 str1 = str1.replace(a, res) 61 else: 62 add = mul_div(str1) # 没有括号时计算乘除 63 a2 = str1.replace(str1, add) # 计算结果代替旧的表达式 64 str1 = rep(str1) 65 res = add_minus(a2) # 计算加减 66 str1 = str1.replace(str1, res) 67 str1 = rep(str1) 68 str1 = add_minus(str1) 69 print(str1) 70 71 print(eval(str1))
时间: 2024-11-05 18:33:52