Chris M. Chris M. - 1 year ago 63
Python Question

Exiting to next loop iteration on successful try

Apologies if this is answered somewhere else here, but I couldn't find it.

I have a

for
loop that queries some points from the OverPass database and then assigns some values to each point depending on the return. Because the return isn't uniform in its tags for all the points, I use a series of
try-catch
statements to assess if a tag is present, what its value is, and then what the assigned value should be. The tags appear in dictionary form, but there is no uniform set of keys.

Example:

for lat, lon in zip(df['PosLat'], df['PosLon']):
...
...
if result.ways:
way = result.ways[0]
try:
if dict[key1] == value1:
#append values to lists
continue
elif dict[key1] == value2:
#append different values to lists
continue
else:
pass
except KeyError:
pass
try:
if dict[key2] == value1:
#append values to lists
continue
elif dict[key2] == value2:
#append different values to lists
continue
elif dict[key2] == value3:
#append still different values to lists
else:
pass
except KeyError:
pass


What I would like to be able to do is exit the current iteration of the for loop when a try block successfully completes, and continue the same iteration if it does not or if an exception is thrown. As my code sits now, multiple values are being appended to
list1
and
list2
on each iteration. I have tried
continue
and
break
, but
continue
seems to be either exiting to the if-statement or back to the try block, and
break
exits the entire for-loop.

I also tried nesting the try-catch statements but that seemed to get very messy and repetitive.

Answer Source

I don't fully understand your problem, but it sounds like you may have a misunderstanding of continue and break. They are simple once you understand how they work and I hope after this explanation you will be able to be able to use them to achieve your goal.

 Continue

continue will simply stop the current iteration, and go to the start of the next iteration.

for i in range(10):
    if i == 5:
        continue
    print(i)

0
1
2
3
4
6 # It skipped 5!
7
8
9

Break

break will exit the entire loop, so no other iterations will happen after.

for i in range(10):
    if i == 5:
        break
    print(i)

0
1
2
3
4
# The entire loop stopped at 5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download