You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自制简易Python解释器if语句执行异常问题求助

问题:简易Python解释器中if语句的缩进代码执行逻辑错误

你的核心问题在于当前实现没有正确跟踪if语句对应的后续连续缩进代码块:

  • 原代码处理if时会遍历所有行中的缩进代码,导致所有if条件为真时都会执行全局所有缩进代码,造成重复执行。
  • 改为遇到非缩进代码就终止的逻辑后,又会直接跳过后续所有行,导致合法的缩进代码(即使在非缩进行之后)无法被处理。

现有实现代码

def tof(c):
    if eval(c) == True:
        return True
    elif eval(c) == False:
        return False

def interpret(code):
    lines = code.splitlines()
    for line in lines:
        if line.startswith("//") or line.strip() == "" or line.startswith("   "):
            continue
        if line.startswith("write(") and line.endswith(")"):
            if line[6] == '"' and line[-2] == '"':
                print(line[7:-2])
            elif line[6:-1].isdigit():
                print(line[6:-1])
            else: # not done yet (variables)
                v = line[6:-1]
                exec(f"print({v})")
        if line.startswith("if ") and line.endswith(" then"):
            one = line.split("if ")[1]
            c = one.split(" then")[0]
            if tof(c) == True:
                for x in lines:
                    if x.startswith("    "):
                        interpret(x.split("    ")[1])
            elif tof(c) == False:
                continue
        if line[2] == "=" or line[1] == "=": # not done yet (variables)
            if line[2] == "=":
                a = line.split(" = ")[0]
                b = line.split(" = ")[1]
                exec(f"{a} = {b}")

code = '''
if 1 + 1 == 2 then
    write("This should execute once!")
if 1 + 3 == 4 then
    // asterisk are there to tell which message is which.
    write("This should execute once! **")
'''

interpret(code)

解决方案:基于索引的代码行遍历

解决思路是放弃for-each循环,改用索引控制的while循环,精确跟踪当前执行位置,仅处理if语句后续的连续缩进块,处理完成后回到正确位置继续执行后续代码。

修改后的代码:

def tof(c):
    # 简化布尔值判断,直接返回表达式的布尔结果
    return bool(eval(c))

def interpret(code):
    lines = code.splitlines()
    index = 0
    while index < len(lines):
        line = lines[index].rstrip()
        index += 1
        
        # 跳过注释和空行
        if line.startswith("//") or line.strip() == "":
            continue
        
        # 处理write语句
        if line.startswith("write(") and line.endswith(")"):
            content = line[6:-1]
            if content.startswith('"') and content.endswith('"'):
                print(content[1:-1])
            elif content.isdigit():
                print(content)
            else:
                exec(f"print({content})")
            continue
        
        # 处理if语句
        if line.startswith("if ") and line.endswith(" then"):
            condition = line.split("if ")[1].split(" then")[0]
            if tof(condition):
                # 执行后续连续的缩进代码块
                while index < len(lines):
                    indent_line = lines[index].rstrip()
                    if indent_line.startswith("    "):
                        interpret(indent_line[4:])
                        index += 1
                    else:
                        break
            else:
                # 条件为假,跳过后续连续的缩进代码块
                while index < len(lines):
                    indent_line = lines[index].rstrip()
                    if indent_line.startswith("    "):
                        index += 1
                    else:
                        break
            continue
        
        # 处理变量赋值
        if " = " in line:
            var_name, expr = line.split(" = ", 1)
            exec(f"{var_name} = {expr}")
            continue

# 测试用例1
print("=== 测试用例1 ===")
code1 = '''
if 1 + 1 == 2 then
    write("This should execute once!")
if 1 + 3 == 4 then
    // asterisk are there to tell which message is which.
    write("This should execute once! **")
'''
interpret(code1)

# 测试用例2
print("\n=== 测试用例2 ===")
code2 = '''
if True then
    write("Hello, World!")
write("Stops here :(")
    write("Never gets here..")
'''
interpret(code2)

关键改进点

  1. 索引控制遍历:用index变量跟踪当前执行的代码行,处理完if的缩进块后,直接从下一行继续执行,避免重复或遗漏。
  2. 缩进块识别:处理if时仅遍历当前if语句后续连续的4空格缩进行,遇到非缩进行立即停止,确保每个if只执行自己对应的代码块。
  3. 假条件处理:条件为假时自动跳过后续的缩进块,不执行也不影响后续代码。
  4. 简化逻辑:精简了tof函数和write、赋值语句的处理逻辑,减少冗余判断。

测试用例1输出:

=== 测试用例1 ===
This should execute once!
This should execute once! **

测试用例2输出:

=== 测试用例2 ===
Hello, World!
Stops here :(
Never gets here..

内容的提问来源于stack exchange,提问作者i_suckatcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 04:00:07