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

Xavier Ho contact at xavierho.com
Fri Jul 17 01:31:28 EDT 2009


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?

Best regards,

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: contact at xavierho.com
Website: http://xavierho.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090717/3fb273f6/attachment.html>


More information about the Python-list mailing list