用python做计算器(高级版)

用python做计算器(高级版)

刚刚闲的不得了,又把计算器升级了

下载库

使用windows带的cmd,用win+打开,输入cmd,再输入pip install sympy

加载库

import sympy

新增功能

if(opeSym != "+" and opeSym != "-" and opeSym != "*" and opeSym != "/" and opeSym != "**" and opeSym != "//" and opeSym != "sqrt" and opeSym != "log" and opeSym != "factorial"):

factorial是阶乘,4的阶乘是4*3*2*1,写作4!

print直接输出结果

print(float(num1) + float(num2))

print()函数里面不仅可以写入string类型,还可以直接写入算式,例如print(x+y)等

为什么要用sympy而不是math

在精确值上面,sympy带来的精确值远比math高。如图所示,在计算根号8乘根号8的时候,math库会给出大于8的答案,这个答案很明显是错的。但是sympy库却给出了正确的答案,所以在计算数学的时候,个人更推荐sympy。

把程序合起来

import sympy

while(1):
    while(1):
        print("--------------------")
        total = 0.0
        num1 = input ("Enter the first number: ")
        if("." in num1):
            pass
        elif(num1.isalnum() == False):
            print("Invalid entering, please enter again.")
            break
        opeSym = input ("Enter your operation: ")
        if(opeSym != "+" and opeSym != "-" and opeSym != "*" and opeSym != "/" and opeSym != "**" and opeSym != "//" and opeSym != "sqrt" and opeSym != "log" and opeSym != "factorial"):
            print("Invalid entering, please enter again.")
            break
        num2 = input ("Enter the second number: ")
        if("." in num2):
            pass
        if(opeSym == "factorial"):
            pass
        elif(num2.isalnum() == False):
            print("Invalid entering, please enter again.")
            break

        if(opeSym == "+"):
            print(float(num1) + float(num2))

        elif(opeSym == "-"):
            print(float(num1) - float(num2))

        elif(opeSym == "*"):
            print(float(num1) * float(num2))

        elif(opeSym == "/"):
            print(float(num1)/float(num2))

        elif(opeSym == "**"):
            print(float(num1)**float(num2))

        elif(opeSym == "//"):
            print(float(num1)//float(num2))

        elif(opeSym == "sqrt"):
            print(sympy.root(float(num1),float(num2)))

        elif(opeSym == "log"):
            print(sympy.log(float(num1),float(num2)))

        elif(opeSym == "factorial"):
            print(sympy.factorial(float(num1)))

效果

虽然也会出现一堆的0,但是这是因为我用的是float型,所以会以这种形式出现。

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

A Python 萌新花花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值