DEV Community

sma
sma

Posted on • Edited on

1 1

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up