[Tutor] Advice for my function, isPrime(n), please

Dick Moores rdm at rcblue.com
Fri Jul 18 22:45:07 CEST 2008


At 12:38 PM 7/18/2008, Kent Johnson wrote:
>On Fri, Jul 18, 2008 at 2:25 PM, Dick Moores <rdm at rcblue.com> wrote:
> > At 10:03 AM 7/18/2008, Kent Johnson wrote:
> >>
> >> On Fri, Jul 18, 2008 at 11:32 AM, Dick Moores <rdm at rcblue.com> wrote:
> >> >    if x == 0:
> >> >        return False
> >> >    else:
> >> >        return True
> >>
> >> Could be just
> >>  return x!=0
> >
> > I see this works, but it's Greek to me. HOW does it work? And why is it
> > better than what I had? Is it faster? Or what?
>
>x != 0 is an expression. The value of that expression is either True
>or False and is returned as the function result.

Huh. Brand new to me. Thanks.

>  It is better because
>it is concise and idiomatic and has exactly the same result as yours.

Is it time to quote this again?

In [15]: import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.  <--
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.  <--
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!


> >> > My question is about whether to test for integerhood. Without that test,
> >> >  isPrime(3.7) returns true, and isPrime('44') returns False. I've gone
> >> > with
> >> > testing for integerhood, and with returning None when n fails the test.
> >>
> >> Better to raise TypeError.
> >
> > Like this?
> > if not isinstance(n, (int, long)):
> >        raise TypeError, "n must be an int or a long"
>
>Yes, though "The argument to isPrime() must be an int or a long" might
>be more expressive.

OK, I'll use it.

Thanks,

Dick
=====================================
Have you seen the video introducing the terrific
and free IDE, Ulipad? Download it from my website.
<http://www.rcblue.com/u3/>



More information about the Tutor mailing list