Try... except....Try again?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Jul 17 10:12:37 EDT 2009


Apologies for breaking threading, but the original post hasn't showed up 
on my ISP's news server.

Xavier Ho wrote:
> I have a simple class that generates prime numbers, using memorisation
> and iteration to generate the next prime number.
[...]
> The next() function generates the next prime, and appends it into
> primes. This way, it keeps trying to append until the nth prime
> requested exist, and returns it.
> 
> My problem is that it's a "While True" loop, which I get a lot of
>> "Don't do it!"

There's nothing wrong with "while True" loops. They are useful in two 
situations:

(1) Where you want to loop forever.

(2) Where you want to loop until some complex event takes place, which 
can't easily be written using "while condition".

Neither of these cases holds for your code, so although there's nothing 
wrong with "while True", in your case I'd avoid it.


> In the light of making the code better, what could I do?


(1) Explicitly loop the correct number of times.
(2) Only catch IndexError.

def nPrime(self, n):
    for i in xrange(len(self.primes), n+1):
        self.next()
    return self.primes[n]



-- 
Steven



More information about the Python-list mailing list