计算器python代码函数
时间: 2023-11-12 10:02:15 浏览: 76
计算器python实现源代码
3星 · 编辑精心推荐
下面是一个计算器Python代码函数的例子:
```python
def calculate(expression):
# 将表达式中的空格删除
expression = expression.replace(' ', '')
# 判断表达式是否为空
if not expression:
return None
# 初始化变量
stack = []
operators = {'+': 1, '-': 1, '*': 2, '/': 2, '%': 2, '^': 3}
result = ''
# 遍历表达式
for i in expression:
# 如果是数字,直接加入结果字符串
if i.isnumeric():
result += i
# 如果是操作符,将前面的数字计算出来并入栈
elif i in operators:
while stack and stack[-1] != '(' and operators[i] <= operators.get(stack[-1], 0):
result += stack.pop()
stack.append(i)
# 如果是左括号,直接入栈
elif i == '(':
stack.append(i)
# 如果是右括号,将栈中的操作符计算出来并加入结果字符串,直到遇到左括号
elif i == ')':
while stack and stack[-1] != '(':
result += stack.pop()
stack.pop()
# 将栈中剩余的操作符计算出来加入结果字符串
while stack:
result += stack.pop()
# 计算结果
stack = []
for i in result:
if i.isnumeric():
stack.append(int(i))
else:
b = stack.pop()
a = stack.pop()
if i == '+':
stack.append(a + b)
elif i == '-':
stack.append(a - b)
elif i == '*':
stack.append(a * b)
elif i == '/':
stack.append(a / b)
elif i == '%':
stack.append(a % b)
elif i == '^':
stack.append(a ** b)
return stack.pop()
```
通过该函数,我们可以将一个数学表达式计算出结果。例如:
```python
expression = '5 + 3 * ( 7 - 2 ) ^ 2'
result = calculate(expression)
print(result)
```
输出为:
```
98
```
阅读全文