2

It's a bit confusing question but here is my (simplified) code.

if (r.status_code == 410):
     s_list = ['String A', 'String B', 'String C']
     for x in in s_list:
         if (some condition):
             print(x)
             break

     print('Not Found')

The thing is, if some condition is satisfied (i.e. x is printed) I don't want 'Not found' to be printed. How can I break out of the outermost if statement?

AndW
  • 726
  • 6
  • 31

3 Answers3

7

You can't break out of an if statement; you can, however, use the else clause of the for loop to conditionally execute the print call.

if (r.status_code == 410):
     s_list = ['String A', 'String B', 'String C']
     for x in in s_list:
         if (some condition):
             print(x)
             break
     else:
         print('Not Found')

print will only be called if the for loop is terminated by a StopIteration exception while iterating over s_list, not if it is terminated by the break statement.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    For confusion about `for` and `else` see [this](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops). – Countour-Integral Jan 20 '21 at 16:26
2

Why not just use a variable?

if (r.status_code == 410):
     s_list = ['String A', 'String B', 'String C']
     found = None
     for x in in s_list:
         if (some condition):
             found = x
             print(x)
             break

     if not found:
         print('Not Found')
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
1

Actually, there's a common mechanism in languages for breaking out of any block, you throw a hissy-fit a.k.a Exception; just make sure you catch it and resume your flow. It all depends what context you find yourself in (coding-standards, performance etc).

It's not as clean as LABELS & JUMP/GO_TO in some languages, but does the trick, I don't mind it.

from builtins import Exception

class JumpingAround(Exception):
    def __init__(self, message=None, data=None, *args, **kwargs):
        super(Exception, self).__init__(message, *args, **kwargs)
        self.data = data

try: #surrounding the IF/BLOCK you want to jump out of
    if (r.status_code == 410):
        s_list = ['String A', 'String B', 'String C']
        for x in s_list:
            if (some condition):
                print(x)
                # break
                raise JumpingAround() # a more complex use case could raise JumpingAround(data=x) when catching in other functions 
        print('Not Found')
except JumpingAround as boing:
  pass
Dharman
  • 30,962
  • 25
  • 85
  • 135