Python代码似乎不按顺序执行

时间:2009-09-25 11:12:39

标签: python debugging

在工作中,我有一种编码在数据库记录中的编程语言。我正在尝试在python中编写一个print函数来显示记录包含的内容。

这是我遇到问题的代码:

    # Un-indent the block if necessary.
    if func_option[row.FRML_FUNC_OPTN] in ['Endif', 'Else']:
        self.indent = self.indent - 1

    # if this is a new line, indent it.
    if len(self.formulatext) <> 0 and self.formulatext[len(self.formulatext) - 1] == '\n':
        for i in range(1,self.indent):
            rowtext = '    ' + rowtext

    # increase indent for 'then', 'else'
    if func_option[row.FRML_FUNC_OPTN] in ['Then', 'Else']:
        self.indent = self.indent + 1

当row.FRML ____ FUNC____OPTN等于'Else'时,我希望它首先取消缩进,然后再次缩进,以便'else'打印在较低的缩进级别,然后其余代码就在其中。相反,这是我得到的缩进类型:

IfThen
        IfThen
            Else
        EndifComment
        IfThen
        Endif
        IfThen
            Else
        Endif
    Else
Endif

正如您所看到的,'Else'仍然比If / Endif更高。知道为什么会这样吗?

我确实尝试使用调试语句来填充代码,其结果是:

row:     Else
row.FRML_FUNC_OPTN is : Elsedecrementing indent
row.FRML_FUNC_OPTN is : Elseincrementing indent

这意味着缩进更改if确实正在输入...

2 个答案:

答案 0 :(得分:2)

仅仅因为它是一种“脚本语言”并不意味着你必须没有带断点的完整调试器!

  • 安装eric3
  • 加载您的代码
  • 按“debug”;)

此外,你似乎是Python的新手,所以这里有一些提示:

  • 你可以乘以字符串,比循环快得多
  • 读取数组访问的工作原理,使用[-1]作为最后一个元素
  • 阅读字符串方法,使用.endswith()
  • 使用元组表示静态不可变数据,更快

&GT;

# Un-indent the block if necessary.
op = func_option[row.FRML_FUNC_OPTN]
if op in ('Endif', 'Else'):
    self.indent -= 1

# if this is a new line, indent it.
if self.formulatext.endswith( '\n' ):
    rowtext = ("\t" * indent) + rowtext

# increase indent for 'then', 'else'
if op in ('Then', 'Else'):
    self.indent += 1

答案 1 :(得分:1)

从调试日志中:

row:     Else
row.FRML_FUNC_OPTN is : Elsedecrementing indent
row.FRML_FUNC_OPTN is : Elseincrementing indent

当您输入提供的代码片段时,我怀疑您在“Else”之前已经有缩进。

尝试添加:

rowtext = rowtext.strip()

在第一个if之前

或者,如果rowtext为空,并且您稍后将其添加到其他内容,请尝试在 上调用strip。