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

MRAB python at mrabarnett.plus.com
Fri Jul 17 09:17:20 EDT 2009


Xavier Ho wrote:
> I have a simple class that generates prime numbers, using memorisation 
> and iteration to generate the next prime number.
> 
> In the class, I have defined a function that gives, say, the 5th prime 
> number. Or the 1000th, it's still very fast. But the code isn't what I 
> really like.
> 
>     def nPrime(self, n):
>         "Returns nth prime number, the first one being 2, where n = 0. 
> When n = 1, it returns 3."
>         while True:
>             try:
>                 return self.primes[n]
>             except:
>                 self.next()
> 
> 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!" In the light of making the code better, what could I do?
> 
I wouldn't use a bare "except". What if you had written "prims" instead
of "primes"? It would catch AttributeError and produce the next prime, 
repeating until it ran out of memory.




More information about the Python-list mailing list