Python Forum

Full Version: at the end of a long loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
sometimes my loops are very long, even in Python. one frequent reason for this is a big case statement or the equivalent bunch of if or elif statements in Python. it results in the top of the loop not being visible at the same time with the bottom of the the loop. in other languages, which have some kind of code at the end of the loop, there is a specific place to append a comment describing the loop (perhaps a copy of the loop control statement, or repeating what the loop is for). in Python, which ends the loop body by unindenting code, there is no place on a specific statement to put such a comment. there is the last line of the loop body right before the fiug.

what i have done is add add a dummy statement. then i put my end of loop comment on that. i usually put a continue statement there, but a pass statement should work just as good, of course, the comment can be placed on a line by itself.

for example:
    for line in lines:
        for ch in line:
            ...
            ...  #lots of lines of code here
            ...
            continue # END: for ch in line:
        ... # maybe some code in between here
        continue # END: for line in lines
Did you have a question ?
I guess the question is: How can I prevent ultra-loops?
Typical answer: Break your code down in simpler functions.


def handle(data):
    """
    You have to shift the code in this function
    """
    return data


for line in lines:
    for ch in line:
        data = handle(line)
        # do something with data
        # use the handle function to parse
        # and transform your data
not really a question ... more of a who thinks my code is $#!+