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