DEV Community

sma
sma

Posted on • Updated on

Lets build a simple interpreter from scratch in python, pt.03: If/Else

Bite sized posts are continuing. In this post we are implementing If keyword:

class Interpreter:

    # ... previous code ...

    def If(self,xs):
        _, cond, trueblock, falseblock = xs
        if self.eval(cond):
            if isinstance(trueblock[0],list):
                for x in trueblock:
                    self.eval(x)
            else:
                self.eval(trueblock)
        else:
            if falseblock:
                if isinstance(falseblock[0],list):
                    for x in falseblock:
                        self.eval(x)
                else:
                    self.eval(falseblock)
code=[

    ["If",True,
       # True block, 3 statements
       [["Print","answer is 42"],
        ["Print","that is 21*2"],
        ["Print","that is just an ordinary number"]],

       # False block
       ["Print","answer is something else"]   
    ],

    ["Print",["Mul","-",42]],

    ["If",False,
       ["Print","answer is 42"],
       ["Print","answer is something else"]   
    ]   
]

interpreter=Interpreter()

interpreter.run(code)
Enter fullscreen mode Exit fullscreen mode

Output:

answer is 42
that is 21*2
that is just an ordinary number
------------------------------------------
answer is something else
Enter fullscreen mode Exit fullscreen mode

Part 4: Comparison functions

Top comments (0)