DEV Community

loading...

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

smadev profile image sma ・1 min read

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)

Output:

answer is 42
that is 21*2
that is just an ordinary number
------------------------------------------
answer is something else

Support me at Patreon
Follow and share on Twitter
Thanks in advance. See you in the next post.
Part 4: Comparison functions

Discussion (0)

pic
Editor guide