用50行Python代码制作一个计算器
2015-11-04 16:36
756 查看
简介在这篇文章中,我将向大家演示怎样向一个通用计算器一样解析并计算一个四则运算表达式。当我们结束的时候,我们将得到一个可以处理诸如 1+2*-(-3+2)/5.6+3样式的表达式的计算器了。当然,你也可以将它拓展的更为强大。 不废话,直接上代码:
注意,因为一开始是木有plyplus模块,所以小伙伴们记得用pip install plyplus来进行安装,最后的效果如图[root@django opt]# python cacl.py
> 1+2*-(-3+2)/5.6+3
4.35714285714
>
#!/usr/bin/env python # -*- coding: utf-8 -*- #_auth by kk # calc.py - # A simple calculator without using eval import operator as op from plyplus import Grammar, STransformer calc_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_operator def 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()
注意,因为一开始是木有plyplus模块,所以小伙伴们记得用pip install plyplus来进行安装,最后的效果如图[root@django opt]# python cacl.py
> 1+2*-(-3+2)/5.6+3
4.35714285714
>
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法