Use 50 lines of Python code to create a calculator

Source: Internet
Author: User

Use 50 lines of Python code to create a calculator
In this article, I will show you how to parse and calculate a four-digit arithmetic expression just like a common calculator. When we end, we will get a calculator that can process expressions such as 1 + 2 *-(-3 + 2)/5.6 + 3. Of course, you can also expand it more powerful. No nonsense. directly add the Code:

#!/usr/bin/env python# -*- coding: utf-8 -*-#_auth by kk# calc.py - # A simple calculator without using evalimport operator as opfrom plyplus import Grammar, STransformercalc_grammar = Grammar("""    start: add;    ?add: (add add_symbol)? mul;    ?mul: (mul mul_symbol)? atom;    @atom: neg | number | '\(' add '\)';    neg: '-' atom;    number: '[\d.]+';    mul_symbol: '\*' | '/';    add_symbol: '\+' | '-';    WS: '[ \t]+' (%ignore);""")class Calc(STransformer):    def _bin_operator(self, exp):        arg1, operator_symbol, arg2 = exp.tail        operator_func = { '+': op.add, '-': op.sub, '*': op.mul, '/': op.div }[operator_symbol]        return operator_func(arg1, arg2)    number      = lambda self, exp: float(exp.tail[0])    neg         = lambda self, exp: -exp.tail[0]    __default__ = lambda self, exp: exp.tail[0]    add = _bin_operator    mul = _bin_operatordef main():    calc = Calc()    while True:        try:            s = raw_input('> ')        except EOFError:            break        if s == '':            break        tree = calc_grammar.parse(s)        print(calc.transform(tree))main()

 

Note: Since the plyplus module is available in the beginning, you may remember to use pip install plyplus for installation. The final effect is [root @ django opt] # python cacl. py> 1 + 2 *-(-3 + 2)/5.6 + 34.35714285714>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.