Python code seems to be getting executed out of order

At work I have a programming language encoded in a database record. I’m trying to write a print function in python to display what the record contains.

This is the code I’m having trouble with:

    # 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

When row.FRML____FUNC____OPTN equals ‘Else’, I expect it to first un-indent, then indent again, so that the ‘else’ is printed at a lower level of indentation, then the rest of the code is within. Instead this is the type of indentation I get:

IfThen
        IfThen
            Else
        EndifComment
        IfThen
        Endif
        IfThen
            Else
        Endif
    Else
Endif

As you can see the ‘Else’ is still indented higher than the If / Endif. Any idea why this could be happening?

I did try sprinkling the code with debug statements the result of which is:

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

which means that the indent altering if’s are indeed being entered…

From your debug log:

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

I suspect you already have indentation before “Else” when you enter the code fragment supplied.

Try adding:

rowtext = rowtext.strip()

just before the first if

Or if rowtext is blank, and you’re adding it to something else later on, try calling strip on that.

Just because it is a “script language” doesn’t mean you have to live without a full debugger with breakpoints !

  • Install eric3
  • Load your code
  • Press “debug” 😉

Also, you seem new to Python, so here are a few hints :

  • you can multiply strings, much faster than a loop
  • read how array access works, use [-1] for last element
  • read on string methods, use .endswith()
  • use tuples for static unmutable data, faster
# 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

Leave a Comment