[Tutor] Advice for my function, isPrime(n), please
kent37 at tds.net
Fri Jul 18 21:38:19 CEST 2008
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. It is better because
it is concise and idiomatic and has exactly the same result as yours.
>> > 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.
More information about the Tutor