Python Forum
at the end of a long loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: at the end of a long loop (/thread-19166.html)



at the end of a long loop - Skaperen - Jun-16-2019

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



RE: at the end of a long loop - Yoriz - Jun-16-2019

Did you have a question ?


RE: at the end of a long loop - DeaD_EyE - Jun-16-2019

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



RE: at the end of a long loop - Skaperen - Jun-16-2019

not really a question ... more of a who thinks my code is $#!+