# [Tutor] best practice

Emile van Sebille emile@fenx.com
Wed, 31 May 2000 05:48:07 -0700

I always convert immediately upon input.

Emile van Sebille
emile@fenx.com
-------------------

----- Original Message -----
From: Timothy Wilson <wilson@visi.com>
To: <tutor@python.org>
Sent: Tuesday, May 30, 2000 9:13 PM
Subject: [Tutor] best practice

> Hi everyone,
>
> Thanks for all of the suggestions with my little prime number program.
As
> several people pointed out, the problem was that raw_input gets a
string
> which sqrt() chokes on. In the interpreter, all it well because the
function
> gets called directly with an integer. OK, problem solved.
>
> That brings up another very picky question though. Where should I
handle
> these type difficulties? Here's another little program I was playing
around
> with that takes an integer and returns a list of the integer's
factors. The
> algorithm is crude, but effective.
>
> wilson@beethoven modules]\$ cat factor.py
> # This function factors an integer and returns a list
>
> from math import *
>
> def factor(number):
> factors = [1, int(number)]
> for i in range(2, sqrt(number) + 1):
> if number % i == 0:
> factors.append(i)
> if i != number/i:   # catch duplicates
> factors.append(int(number/i))
> factors.sort()
> return factors
>
> if __name__ == '__main__':
> number = raw_input("Factor what? ")
> print factor(float(number))
>
> As you can see, I convert the raw_input to a float before passing it
to the
> function. Also, I have a couple of int() functions in my factor
function to
> make sure that the list which is returned is a list of integers.
**When run
> from the interpreter, those int()s aren't needed.**
>
> So here's the question (it's about time :-). Is it better python
practice to
> make those type conversion outside the function or inside as I've
done?
> Should the functions be made as "pure" as possible? It seems to me
that for
> maximum efficiency, a rule of thumb should be that functions should be
> to work in the interpreter with a minimum of fuss. The programmer who
uses
> the function (or module) should be the one who concerns himself with
the
> "types" of variables that are passed.
>
> Does this make any sense? (I've been grading 10-page research papers
from
swim.)
>
> -Tim
>
> --
> Tim Wilson      | Visit Sibley online:         | Check out:
> Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/
> W. St. Paul, MN |                              | http://slashdot.org/
> wilson@visi.com |   <dtml-var pithy_quote>     | http://linux.com/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://www.python.org/mailman/listinfo/tutor
>