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

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo πŸ“Šβœ¨

Top comments (0)

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay