python if语句四则运算_python 一遍式四则运算

#!/usr/bin/python

#coding: utf-8

INTEGER = 'INTEGER'

PLUS = '+'

MINUS = '-'

MUL = '*'

DIV = '/'

LC = '('

RC = ')'

EOF = 'EOF'

class Token(object):

def __init__(self, typ, val):

self.typ = typ;

self.val = val;

def __str__(self):

return "Token('{typ}','{val}')".format(typ=self.typ, val=self.val)

def __repr__(self):

return self.__str__()

class Lexer(object):

def __init__(self, text):

self.text = text

self.pos = 0

self.cur_token = None;

self.status = 0

def next_token(self):

if self.pos > len(self.text) -1:

return Token(EOF, '')

ch = ''

while True:

ch = self.text[self.pos]

self.pos+=1

if (ch!=' ' and ch!='\t'):

break;

if self.status==0:

if ch.isdigit():

self.status = 1

return Token(INTEGER, int(ch + self.next_token().val))

else:

return Token(ch, ch)

elif self.status==1:

if ch.isdigit():

return Token(INTEGER, ch + self.next_token().val)

else:

self.pos -= 1

self.status = 0

return Token(INTEGER, '')

class Interpreter(object):

def __init__(self, lexer):

self.lexer = lexer

self.cur_token = lexer.next_token()

def error(self):

raise Exception("syntax error")

def eat(self, typ):

tok = self.cur_token

if (tok.typ == typ):

self.cur_token = self.lexer.next_token()

return tok.val

else:

self.error()

def factor(self):

if (self.cur_token.typ == INTEGER):

tok = self.cur_token

self.eat(INTEGER)

return tok.val

elif self.cur_token.typ == LC:

self.eat(LC)

result = self.expr()

self.eat(RC)

return result

else:

self.error()

def term(self):

result = self.factor()

while self.cur_token.typ in (MUL, DIV):

if (self.cur_token.typ==MUL):

self.eat(MUL)

result = result * self.factor()

elif (self.cur_token.typ==DIV):

self.eat(DIV)

result = result / self.factor()

return result

def expr(self):

result = self.term()

while self.cur_token.typ in (PLUS, MINUS):

if (self.cur_token.typ==PLUS):

self.eat(PLUS)

result = result + self.term()

elif (self.cur_token.typ==MINUS):

self.eat(MINUS)

result = result - self.term()

return result

def main():

print("expr2")

while True:

text = raw_input("calc> ")

if not text:

continue

if text=="exit":

break;

lex = Lexer(text)

calc = Interpreter(lex)

result = calc.expr()

print(result)

if __name__ == "__main__":

main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值