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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM