利用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()

  

猜你喜欢

转载自www.cnblogs.com/liaoxuewen/p/10405880.html
今日推荐