Search code examples
python

Python - Break out of if statement in for loop in if statement


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?


Solution

  • 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.