高级计算器python代码
时间: 2023-07-09 13:48:27 浏览: 87
以下是一个简单的Python高级计算器代码:
```python
import math
def calculate():
print("欢迎使用高级计算器!")
while True:
print("请输入要计算的表达式,输入Q退出:")
expression = input()
if expression == "Q":
break
try:
result = eval(expression)
print("计算结果为:", result)
except ZeroDivisionError:
print("除数不能为零!")
except NameError:
print("输入的表达式有误!")
except:
print("未知错误!")
calculate()
```
这个计算器支持基本的四则运算,以及一些高级函数,如sin、cos、tan、log等。当用户输入一个表达式时,程序将对其进行求值,并将结果输出到屏幕上。如果表达式有误,程序将输出错误信息。用户可以输入Q来退出计算器。
相关问题
小米计算器python源代码
小米计算器Python源代码同样可以实现基础的四则运算和括号运算。下面给出一个简单的小米计算器Python源码示例:
```
# -*- coding: utf-8 -*-
'''
小米计算器Python程序
'''
import re
def calculate(s):
# 去掉空格
s = s.replace(' ', '')
# 将连续的+,-符号替换为单个符号
s = re.sub('-+', '-', s)
s = re.sub('\++', '+', s)
# 将表达式中的数字和符号分开
pattern = re.compile(r'(\d+\.?\d*)|([+\-\*/\(\)])')
expr_list = pattern.findall(s)
# 将表达式转化为逆波兰表达式
stack = []
postfix_list = []
for i in expr_list:
if i[0]|i[1] == '':
continue
elif i[1] in ['+', '-']:
while stack and stack[-1] != '(':
postfix_list.append(stack.pop())
stack.append(i[1])
elif i[1] in ['*', '/']:
while stack and stack[-1] in ['*', '/']:
postfix_list.append(stack.pop())
stack.append(i[1])
elif i[1] == '(':
stack.append(i[1])
elif i[1] == ')':
while stack and stack[-1] != '(':
postfix_list.append(stack.pop())
stack.pop()
else:
postfix_list.append(i[0])
while stack:
postfix_list.append(stack.pop())
# 计算逆波兰表达式
stack = []
for i in postfix_list:
if i[0] == '':
continue
elif i[0] not in ['+', '-', '*', '/']:
stack.append(float(i[0]))
else:
if i[0] == '+':
a = stack.pop()
b = stack.pop()
stack.append(a+b)
elif i[0] == '-':
a = stack.pop()
b = stack.pop()
stack.append(b-a)
elif i[0] == '*':
a = stack.pop()
b = stack.pop()
stack.append(a*b)
else:
a = stack.pop()
b = stack.pop()
stack.append(b/a)
return stack.pop()
if __name__ == '__main__':
# 测试程序
print(calculate('1+2*(3+4)-5/2'))
```
以上Python源代码实现了小米计算器的功能,通过输入表达式进行四则运算并返回结果。它支持加减乘除、带括号的表达式,可以正确处理优先级和左右结合性。如果需要实现更多高级算法,可以根据现有代码进行修改和扩展。
python计算器代码
以下是一个简单的 Python 计算器代码示例:
```python
# 定义一个函数来执行数学运算
def calculate():
operation = input('请选择操作(+, -, *, /): ')
if operation not in ['+', '-', '*', '/']:
print('无效的操作符')
return
num1 = float(input('请输入第一个数字: '))
num2 = float(input('请输入第二个数字: '))
if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
else:
result = num1 / num2
print('结果为: ', result)
# 调用 calculate 函数
calculate()
```
这个示例只实现了基本的加减乘除运算。如果你需要更高级和复杂的计算器功能,你需要实现更多的代码逻辑。