Python Forum
at the end of a long loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
at the end of a long loop
#1
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
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Did you have a question ?
Reply
#3
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
not really a question ... more of a who thinks my code is $#!+
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020