Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 985
AndW Avatar asked Oct 20 '25 14:10

AndW


1 Answers

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.

like image 102
chepner Avatar answered Oct 22 '25 04:10

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!