File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Open diff view settings
Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Open diff view settings
Original file line number Diff line number Diff line change 1+ class Interpreter :
2+ def __init__ (self ):
3+ self .variables = {}
4+
5+ def interpret (self , code ):
6+ tokens = code .split ()
7+ if len (tokens ) < 3 :
8+ raise SyntaxError ("Invalid syntax" )
9+
10+ if tokens [1 ] != "=" :
11+ raise SyntaxError ("Invalid assignment" )
12+
13+ variable = tokens [0 ]
14+ operator = tokens [2 ]
15+ value = int (tokens [3 ])
16+
17+ if operator == "+" :
18+ self .variables [variable ] = self .variables .get (variable , 0 ) + value
19+ elif operator == "-" :
20+ self .variables [variable ] = self .variables .get (variable , 0 ) - value
21+ elif operator == "*" :
22+ self .variables [variable ] = self .variables .get (variable , 0 ) * value
23+ elif operator == "/" :
24+ self .variables [variable ] = self .variables .get (variable , 0 ) / value
25+ else :
26+ raise SyntaxError ("Invalid operator" )
27+
28+ return self .variables [variable ]
29+
30+
31+ interpreter = Interpreter ()
32+ code = input ("Enter code: " )
33+ result = interpreter .interpret (code )
34+ print ("Result:" , result )
35+
You can’t perform that action at this time.
0 commit comments