Why do I require an "elif" statement here?

Justin Azoff justin.azoff at gmail.com
Fri Aug 4 14:20:37 EDT 2006


Jim wrote:
> Could somebody tell me why I need the "elif char == '\n'" in the
> following code?
> This is required in order the pick up lines with just spaces in them.
> Why doesn't
> the "else:" statement pick this up?

No idea.  Look at the profile of your program: for.. if.. for.. if..
else.. if..  This is NOT good.  The reason why you are having trouble
getting it to work is that you are not writing it in a way that is easy
to debug and test.  If one block of code ends up being indented halfway
across the screen it means you are doing something wrong.

This program should be split up into a handful of small functions that
each do one thing.  The following is slightly longer, but immensely
simpler.  Most importantly, it can be imported from the python shell
and each function can be tested individually.

def leading_spaces(line):
    """Return the number of leading spaces"""
    num = 0
    for char in line:
        if char != ' ':
            break
        num += 1
    return num

def change_indent(line, old, new):
    """Change the indent of this line using a ratio of old:new"""
    ws = leading_spaces(line)

    #if there was no leading whitespace,
    #or it wasn't a multiple of the old indent, do nothing
    if ws == 0 or ws % old:
        return line

    #otherwise change the indent
    new_spaces = ws/old*new
    new_indent = ' ' * new_spaces
    return new_indent + line.lstrip(' ')


def reindent(ifname, ofname, old, new):
    f = open(ifname)
    o = open(ofname, 'w')

    for line in f:
        line = change_indent(line, old, new)
        o.write(line)

    f.close()
    o.close()

if __name__ == "__main__":
    try :
        ifname, ofname, old, new = sys.argv[1:]
        old = int(old)
        new = int(new)
    except ValueError:
        print "blah"
        sys.exit(1)

    reindent(ifname, ofname, old, new)




More information about the Python-list mailing list