目录
前言
一个朴实无华的加减乘除四则运算,帮崽崽戒掉扣手指头的习惯。
一、❥(^_-)实现案例
1、❥(^_-)思路
将崽崽的家庭作业,统一按固定格式整理好,存到一个字符串内,然后通过有规则的截取,比如换行符。好的我们来看看崽崽的作业。计算下面的四则运算值:
1+2
3+4
5-3
4*3
10/2
2、❥(^_-)实现代码及效果
# -*- coding: UTF-8 -*-
import re
def naive_calc(code):
code_lines = [l for l in code.split('\n') if l.strip() != '']#按字符串的行结尾字符截取,如换行符\n,将转化后的结果存入列表中。
for line in code_lines:
ret = re.match("\s*(\d+)([\+\-\*\/])(\d+)\s*", line)
left = ret.group(1)
op = ret.group(2)
right = ret.group(3)
if op == '+':
print('{}+{}={}'.format(left, right, int(left)+int(right)))
elif op == '-':
print('{}-{}={}'.format(left, right, int(left)-int(right)))
elif op == '*':
print('{}*{}={}'.format(left, right, int(left)*int(right)))
elif op == '/' and right != '0':
print('{}/{}={}'.format(left, right, int(left)/int(right)))
def test():
code = '''
1+2
3+4
5-3
4*3
10/2
'''
naive_calc(code)
if __name__ == '__main__':
test()
效果图:
二、❥(^_-)总结
快去拿给你崽崽玩吧,让他自己完成作业。