Python代码执行顺序似乎不正确
在工作中,我有一种编程语言的内容存储在数据库记录里。我正在尝试用Python写一个打印函数,来显示这个记录里包含的内容。
这是我遇到问题的代码:
# 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
这意味着改变缩进的条件确实被执行了……
2 个回答
2
虽然它被称为“脚本语言”,但这并不意味着你就不能使用带有断点的完整调试工具!
- 安装 eric3
- 加载你的代码
- 点击“调试”按钮;)
另外,看起来你对 Python 还不太熟悉,这里有一些小建议:
- 你可以用更快的方式来重复字符串,而不是用循环。
- 了解一下数组的访问方式,使用 [-1] 可以获取最后一个元素。
- 看看字符串的方法,使用 .endswith() 来检查字符串是否以某个特定的内容结尾。
- 使用元组来存储不变的数据,这样会更快。
# 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
根据你的调试日志:
row: Else
row.FRML_FUNC_OPTN is : Elsedecrementing indent
row.FRML_FUNC_OPTN is : Elseincrementing indent
我怀疑在你提供的代码片段中,“Else”前面已经有缩进了。
你可以试着在:
rowtext = rowtext.strip()
第一个 if 之前加上这个。
或者如果 rowtext 是空的,而你之后要把它加到其他地方,可以试着对那个使用 strip。