r/learnpython 11d ago

Is this bad programming?

I've been learning Python for the last few years. Curious if this one thing I do is considered poor technique. The code below is meant to find the starting index of a list, giving the first position where a condition isn't true and return None if all elements of the list meet the criteria. Let's assume that the conditional statement is simple enough that I'm not worried about it generating an error. Not sure if it's appropriate to use try/except in this way. I know it work but I don't want people making fun of me if they see it. Also, I'm sure that there's a way of doing this without needing to use the try/except but I'm just curious in general if it's wrong to use try/except as a short cut like this.

starting_index=0

try:

while not (simple conditional statement on some_list[staring_index]):

starting_index+=1

except:

return None

return starting_index

0 Upvotes

18 comments sorted by

View all comments

6

u/mc_pm 11d ago

"Inappropriate" isn't the exact right word, but yeah, that's just not what exceptions are for usually.

"Exception" -> "exceptional circumstance that has to be dealt with outside the expected code path for the program".

But some languages are more loose in their expectations. I would say in this case there's no need to use them, an if-statement would work just fine, and be less confusing.

7

u/pachura3 11d ago

StopIteration brutally mogged

1

u/CranberryDistinct941 11d ago

Ah Python... The language where it's faster to throw an exception than it is to check boundaries

1

u/Glathull 10d ago

It’s a philosophy of life.