python 计算器实现,包含标准、科学、程序员
时间: 2023-07-10 12:08:51 浏览: 93
python计算器的实现
以下是一个简单的 Python 计算器实现,包含标准、科学、程序员三种模式:
```python
import math
def standard():
while True:
try:
expr = input("请输入表达式(输入 q 退出):")
if expr == 'q':
break
result = eval(expr)
print("结果为:", result)
except:
print("表达式无效,请重新输入!")
def scientific():
while True:
try:
print("请选择功能:")
print("1. sin(x)")
print("2. cos(x)")
print("3. tan(x)")
print("4. log(x)")
print("5. e^x")
print("6. x^y")
print("7. sqrt(x)")
print("8. 退出")
choice = int(input("请选择功能:"))
if choice == 8:
break
elif choice == 1:
x = float(input("请输入 x:"))
result = math.sin(x)
print("sin({}) = {}".format(x, result))
elif choice == 2:
x = float(input("请输入 x:"))
result = math.cos(x)
print("cos({}) = {}".format(x, result))
elif choice == 3:
x = float(input("请输入 x:"))
result = math.tan(x)
print("tan({}) = {}".format(x, result))
elif choice == 4:
x = float(input("请输入 x:"))
result = math.log(x)
print("log({}) = {}".format(x, result))
elif choice == 5:
x = float(input("请输入 x:"))
result = math.exp(x)
print("e^{} = {}".format(x, result))
elif choice == 6:
x = float(input("请输入 x:"))
y = float(input("请输入 y:"))
result = math.pow(x, y)
print("{}^{} = {}".format(x, y, result))
elif choice == 7:
x = float(input("请输入 x:"))
result = math.sqrt(x)
print("sqrt({}) = {}".format(x, result))
else:
print("请选择正确的功能!")
except:
print("输入有误,请重新输入!")
def programmer():
while True:
try:
print("请选择进制:")
print("1. 二进制")
print("2. 八进制")
print("3. 十进制")
print("4. 十六进制")
print("5. 退出")
choice = int(input("请选择进制:"))
if choice == 5:
break
elif choice == 1:
x = input("请输入 x:")
x = int(x, 2)
print("十进制:", x)
print("八进制:", oct(x))
print("十六进制:", hex(x))
elif choice == 2:
x = input("请输入 x:")
x = int(x, 8)
print("十进制:", x)
print("二进制:", bin(x))
print("十六进制:", hex(x))
elif choice == 3:
x = int(input("请输入 x:"))
print("二进制:", bin(x))
print("八进制:", oct(x))
print("十六进制:", hex(x))
elif choice == 4:
x = input("请输入 x:")
x = int(x, 16)
print("十进制:", x)
print("二进制:", bin(x))
print("八进制:", oct(x))
else:
print("请选择正确的进制!")
except:
print("输入有误,请重新输入!")
print("请选择模式:")
print("1. 标准模式")
print("2. 科学模式")
print("3. 程序员模式")
mode = int(input("请选择模式:"))
if mode == 1:
standard()
elif mode == 2:
scientific()
elif mode == 3:
programmer()
else:
print("请选择正确的模式!")
```
该计算器实现了三种模式:
- 标准模式:可以进行常规的加减乘除运算,输入 q 退出;
- 科学模式:可以进行 sin、cos、tan、log、e^x、x^y、sqrt 等运算,选择 8 退出;
- 程序员模式:可以进行二进制、八进制、十进制、十六进制间的转换,选择 5 退出。
阅读全文