DEV Community

sma
sma

Posted on • Edited on

Lets build a simple interpreter from scratch in python, pt.06: While loop

In this post we are implementing the 'while' loop:

class Interpreter:

    # ....(previous code)....

    def While(self,xs):
        _ , cond , block = xs
        while self.eval(cond):
            if isinstance(block[0],list):
                for x in block:
                    self.eval(x)
            else:
                self.eval(block)

code=[

    ["Set","sum",0],

    ["Set","i",0],

    ["While", ["Lt", ["Get","i"], 100], [

        ["Set","i", ["Add",["Get","i"], 1] ],
        ["Set","sum", ["Add",["Get", "sum"],["Get","i"]]]
    ]],

    ["Print","sum(1..100) = ",["Get","sum"] ]
]

interpreter=Interpreter()

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

Output:

sum(1..100) = 5050
Enter fullscreen mode Exit fullscreen mode

Link to complete code: part6
Links: Patreon Twitter

Part 7: Break and Continue

Top comments (0)