DEV Community

sma
sma

Posted on • Edited on

1 1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay