I am new to django and thought of doing to simple django application to learn more about it, In one of the places in code I had to pick locationName
and getting elements that matched same id as locationName
in a table. When I started wondering is continue
the most pythonic way to escape a for-loop?
Code in question is given below :
for locationName in locationGroup:
idRef = locationName.id
try:
element = location.objects.order_by('-id').filter(name__id=idRef)[0]
except IndexError:
continue
If there's some code you don't want getting executed after the except clause, continue
is perfectly valid, otherwise some might find pass
more suitable.
for x in range(y):
try:
do_something()
except SomeException:
continue
# The following line will not get executed for the current x value if a SomeException is raised
do_another_thing()
for x in range(y):
try:
do_something()
except SomeException:
pass
# The following line will get executed regardless of whether SomeException is thrown or not
do_another_thing()
That's exactly what the continue
/break
keywords are for, so yes, that's the simplest and most pythonic way of doing it.
There should be one-- and preferably only one --obvious way to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With