Cleaning up nested if statements to be more readable - python

1 minute read

Nested IF statements can be quite annoying. While they generally work and the code may function correctly, it can be challenging to understand what a particular part of the code is intended to do.

Ugly code:

 1for m in range(3):
 2    for n in range(3):
 3        if m!=0:
 4            if m!=n:
 5                print (m, n)
 6# Output:
 71 0
 81 2
 92 0
102 1

Continue statement, skip the remaining code inside a loop for the current iteration. Much better.

 1for m in range(3):
 2    for n in range(3):
 3        if m==0:
 4            continue
 5        if m==n:
 6            continue
 7        print (m, n)
 8
 9# Output:
101 0
111 2
122 0
132 1