Frankenmint
Frankenmint

Reputation: 1633

How do I exit a for loop in python 2.7 without raising Exceptions

I have a for loop that iterates across a list of floats. My original intention was that I could do a for loop with an if statement to 'do stuff' if my data is > than x percentage…however I've come to realize that this method causes duplication of data presented. It IS factually right, but it is not what I desired nor intended. So, my mock data has something that is way larger than reality and it triggers the if condition on all lower percentages. I really just want it to trigger on the largest percentage and not onto the smaller conditions below…how would I do that in the most pythonic way possible?

This is the sample code solution I threw together but I think having to involve raising exceptions using a try/catch block is probably not as clean as other solutions.

#!/usr/bin/env python

percentages =  [0.2,0.5, 0.75, 1, 2, 5]
resultingPercentage = 9


for i in sorted(percentages, reverse=True):
    try:
        if resultingPercentage > i:
            print "We found an opportunity greater than %.2f%% points" %i
            raise Exception
    except:
        #continue
        break

Upvotes: 0

Views: 494

Answers (2)

Nick is tired
Nick is tired

Reputation: 7056

Seeing as nobody else has posted it as an answer yet and to mark this question as answered, you can break out of a loop without the break statement appearing in an exception handler:

percentages =  [0.2,0.5, 0.75, 1, 2, 5]
resultingPercentage = 9

for i in sorted(percentages, reverse=True):
    if resultingPercentage > i:
        print "We found an opportunity greater than %.2f%% points" %i
        break

Upvotes: 1

Marek Pokorny
Marek Pokorny

Reputation: 153

You can use the max function to get the largest percentage from the list, then just do a single if statement with only that percentage:

percentages =  [0.2,0.5, 0.75, 1, 2, 5]
resultingPercentage = 9
maxPercentage = max(percentages)
if resultingPercentage > maxPercentage:
    print "We found an opportunity greater than %.2f%% points" %maxPercentage

Upvotes: 0

Related Questions