• 利用eval函数实现简单的计算器


    """
    description : use python eval() function implement a simple calculator
    functions can be used as follow:
    ----------------------------------------
    + : addition
    - : minus
    * : multiplication
    / : division
    % : --> /100.0
    e : math.e
    pi : math.pi
    sin : math.sin
    cos : math.cos
    ^ : --> **
    tan : math.tan
    mod : --> %
    sqrt: math.sqrt
    rad: --> radius math.radians
    round:
    """
    import math
    
    # 定义可以使用的函数及常量
    functions=('e','pi','sin','cos','tan','sqrt','radians')
    
    def calculate(expression):
    
        expression=expression.lower()
    
        # replace函数返回替换后的字符串
        expression=expression.replace('%','/100.0')
        expression=expression.replace('^','**')
        expression=expression.replace('mod','%')
        expression=expression.replace('rad','radians')
    
        for i in functions:
            if i in expression:
                expression=expression.replace(i,'math.{}'.format(i))
        try:
            return (eval(expression))
        except ZeroDivisionError:
            print('zero can not be division')
        except Exception as e:
            print(e)
    
    def main():
        while True:
            expression=input("input your expression here:")
            if expression=='q':
                break
            else:
                result=calculate(expression)
                if result:
                    print(result)
    
    
    if __name__=="__main__":
        main()
    

      

  • 相关阅读:
    PAT 1032 (未完成)
    PAT 1031
    PAT 1030
    将爬取到的数据存入数据框并导出
    XPath常见用法
    python 图表
    Protobuf在Unity中的通讯使用
    ProtoBuf在Unity中的使用
    Unity更新资源代码
    匿名函数
  • 原文地址:https://www.cnblogs.com/liaoxuewen/p/10405880.html
Copyright © 2020-2023  润新知