[PYTHON] Get out of multiple loops at once

Python doesn't provide an easy way to get out of multiple loops. You can prepare a flag, but it's not very beautiful

python


flag = False
for i in range(100):
    for j in range(100):
        if i > j > 70:
            flag = True
            break
        print i, j
    if flag:
        break

I think that such a for loop can be reviewed from the structure. There are times when I want you to break out of multiple loops. In such a case

Use the for-else clause

python


for i in range(100):
    for j in range(100):
        if i > j > 70:
            break
        print i, j
    else:
        continue
    break

Not so beautiful

Use try-except syntax

python


try:
    for i in range(100):
        for j in range(100):
            if i > j > 70:
                raise Exception
            print i, j
except Exception:
    pass

It's different from the original usage and I can't really like it ~

use goto

goto for Python

python


from goto import goto, label

for i in range(100):
    for j in range(100):
        if i > j > 70:
            goto .END
        print i, j
label .END

Easy to understand but requires installation of external modules

All of them are not good enough, and they should be made into functions. Yes.

Recommended Posts

Get out of multiple loops at once
Get a lot of Twitter tweets at once
Rsync multiple files at once
[Laravel] Aliase to create migration file of multiple tables at once
Delete unnecessary containers of Docker at once
Get AKB member's Google+ ID at once
Update multiple tables at once with pandas to_sql
Convert multiple proto files at once with python
Register multiple self-made styles in Word at once
Get corporate number at once via gbizinfo with python
Get the sum of each of multiple columns with awk
Multiple inheritance of classes
Copy of multiple List
I made a tool to get the answer links of OpenAI Gym all at once
Get UNIXTIME at the beginning of today with a command
[Linux] Grep multiple gzip files in a directory at once
Create multiple users with serial numbers at once with Ansible Playbook