首页 > 代码库 > week4_day6(计算器)

week4_day6(计算器)

本文主要是实现:计算器的应用,本人历经三天,费了九牛二虎之力,希望大家多多捧场,还有很多功能不完善,正在更新中·····                                                  

 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 s15 16 17 # 检查是否合法18 def checkout(s):19     flag = True20     if re.findall([a-zA-Z], s):21         print(您可能输入了字母或特殊字符,请重新输入!)22         flag = False23     return flag24 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 s36 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 s49 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))

 

week4_day6(计算器)