DEV Community

sma
sma

Posted on • Edited on

1

Lets build a simple interpreter from scratch in python, pt.08: For loop

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

class Interpreter:
    def __init__(self):
        self.scope=[{}]
        self.loop_stack=[]

    # ...(previous code)...

    # 'For' loop is not much different from 'while' loop
    # for(inits; cond; increments) {block}

    def For(self,xs):
        self.loop_stack.append({"break":False,"continue":False})        
        _, inits, cond, increments, block = xs
        for x in inits: 
            self.eval(x)
        while self.eval(cond):
            if isinstance(block[0],list):
                for x in block:
                    self.eval(x)
                    if self.loop_stack[-1]["break"]:
                        self.loop_stack.pop()
                        return
                    if self.loop_stack[-1]["continue"]:
                        self.loop_stack[-1]["continue"]=False
                        break
            else:
                self.eval(block) 
            for x in increments:
                self.eval(x)
        self.loop_stack.pop()

code=[

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

    ["For", [["Set","i",0]], 
            ["Lt", ["Get","i"], 100], 
            [["Set","i", ["Add",["Get","i"], 1] ]],   
    [   

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

        ["Print","i=",["Get","i"],", sum=",["Get","sum"]],

        ["If", ["Eq", ["Get", "i"], 10], 
             ["Break"],[]
        ],


    ]],

]

interpreter=Interpreter()

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

Output:

i=0, sum=0
i=1, sum=1
i=2, sum=3
i=3, sum=6
i=4, sum=10
i=5, sum=15
i=6, sum=21
i=7, sum=28
i=8, sum=36
i=9, sum=45
i=10, sum=55
Enter fullscreen mode Exit fullscreen mode

Link to complete code.

Part 9: Function,Call,Return

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

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