简体   繁体   中英

How to loop back in python to specific point

I have a code:

I want my program to go back to for loop after the 3rd if statement is executed. When I use "continue" it goes back to the 2nd if statement and not back to the for loop. Any idea how to accomplish this? Thanks.

row = 0  
for line in fh:

    if line.startswith('CREATE'):
        startrow = row
    if row > startrow:
        if line.startswith('PRIMARY KEY'): (then go to the for loop)
        print row
    row = row + 1

Per the description in the comment, you're looking to print ranges of lines matching certain conditions, much like awk '/^CREATE/,/^PRIMARY KEY/ {print}' . For some reason you've planned this with a goto, from a concept of nested loops, which are just not present. We could write nested loops, but we don't need to.

printing = False
for line in fh:
    if line.startswith('PRIMARY KEY'):
        printing = False
    if printing:
        print row
    if line.startswith('CREATE'):
        printing = True

This variant starts out not printing lines, starts printing lines after encountering CREATE, and stops again immediately upon encountering PRIMARY KEY. You can reorder the three tests to achieve other combinations like printing the lines containing those keywords.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM