python计算器


python 计算器代码

 

 1 import re
 2 def add_sub(a_s):
 3     if '--'in a_s:
 4         a_s=a_s.replace('--','+')
 5     a_s=re.findall('\-?\d+\.?\d*',a_s)
 6     ls=[]
 7     for i in range(len(a_s)):
 8         ls.append(float(a_s[i]))
 9     return str(sum(ls))
10 def mul_div(m_d):
11     while True:
12         m_d01=re.search(r'\d+\.?\d*[*/](\d+\.?\d*)',m_d)
13         if m_d01==None:return m_d
14         if '*' in m_d01.group():
15             m_d02=re.findall(r'\d+\.?\d*',m_d01.group())
16             result=float(m_d02[0])*float(m_d02[1])
17             m_d=re.sub(r'\(?\d+\.?\d*\*(\d+\.?\d*)\)?',str(result),m_d,1)
18         elif '/'in m_d01.group():
19             m_d03=re.findall(r'\d+\.?\d*',m_d01.group())
20             result=float(m_d03[0])/float(m_d03[1])
21             m_d = re.sub(r'\(?\d+\.?\d*\/(\d+\.?\d*)\)?',str(result),m_d, 1)
22         else:break
23     return m_d
24 def result_all(r_a):
25     while True:
26         if re.findall('[*/]',r_a):
27             r_a=mul_div(r_a)
28         if re.findall('[+-]',r_a):
29             r_a=add_sub(r_a)
30         else:break
31     return r_a
32 def remove_brackets(r_b):
33     while True:
34         if '('in r_b:
35             r_b1=re.search(r'\([^()]+\)',r_b)
36             r_b1=result_all(r_b1.group())
37             r_b=re.sub(r'\([^()]+\)',str(r_b1),r_b,1)
38         else:break
39     return result_all(r_b)
40 while True:
41     run_num="".join(input(">>输入计算公式:").split())
42     print(remove_brackets(run_num.strip()))
View Code

python实现计算器加减乘除带括号代码

 

posted @ 2017-10-08 21:29  python学到老  阅读(234)  评论(0)    收藏  举报