python, pt.03: If/Else에서 처음부터 간단한 인터프리터를 구축할 수 있습니다.
                                            
                                                
                                                
                                                
                                                
                                                
                                                 5172 단어  pythonfromscratchinterpreter
                    
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)
산출:
answer is 42
that is 21*2
that is just an ordinary number
------------------------------------------
answer is something else
Patreon에서 저를 지원하십시오
팔로우 및 공유
미리 감사드립니다. 다음 포스팅에서 뵙겠습니다.
Reference
이 문제에 관하여(python, pt.03: If/Else에서 처음부터 간단한 인터프리터를 구축할 수 있습니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/smadev/lets-build-a-simple-interpreter-from-scratch-in-python-pt-03-if-else-511h텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)