[Tutor] why the error?
Wesley J. Chun
wesc@alpha.ece.ucsb.edu
Tue, 30 May 2000 13:22:50 -0700 (PDT)
> Date: Tue, 30 May 2000 14:41:29 -0500 (CDT)
> From: Timothy Wilson <wilson@visi.com>
>
> I wrote a little function that determines whether a given number is prime or
> not. (I'm pretty sure the algorithm is correct.)
>
> --snip--
> from math import *
>
> def isPrime(number):
> for j in range(2, sqrt(number)+1):
> if number % j == 0:
> return 0
> return 1
>
> if __name__ == '__main__':
> number = raw_input("Which number? ")
> if isPrime(number):
> print "%i is prime." % number
> print "%i is not prime." % number
> --snip--
>
> This code seems to work perfectly when imported in the interpretor. When I
> run it by typing 'python prime.py', I get:
>
> [wilsont@galileo python]$ python prime.py
> Which number? 11
> Traceback (innermost last):
> File "prime.py", line 15, in ?
> if isPrime(number):
> File "prime.py", line 8, in isPrime
> for j in range(2, sqrt(number)+1):
> TypeError: illegal argument type for built-in operation
>
> Any hints? Why the difference?
well, guess what. it should *not* have worked in the interpreter either.
the problem with the code is here:
> for j in range(2, sqrt(number)+1):
the reason why you get a TypeError is because the sqrt()
function expects a floating point number. you passed in
a string. the string comes from raw_input():
> number = raw_input("Which number? ")
the raw_input() built-in function returns a raw string of
what the user enters.
to fix the bug, you have two choices:
1) leave it as a string input from the user using raw_input()
and convert that value to a float, i.e. you can do it in
different places, i.e.
number = float(raw_input("Which number? "))
or
if isPrime((float(number)):
or even
for j in range(2, sqrt(float(number))+1):
note that if you are using an older version of python where
strings are not accepted input for float(), you would have
to use string.atof().
(2) use input() to evaluate the string expression input.
input() is really the same as eval(raw_input()).
so if you type in any object, they will be represented as
such by eval() and returned, i.e. if the user enters an int,
you can an int, if they enter a list, you get a list, etc.
i would probably recommend option (1) because at least you
are guaranteed you get a float out of it.
finally, i am not familiar with the "%i" directive for the
string format operator:
> print "%i is prime." % number
do you mean "%d" for integer?
hope this helps!!
-wesley
"Core Python Programming", Prentice-Hall, TBP Summer 2000
wesley.j.chun :: wesc@alpha.ece.ucsb.edu
cyberweb.consulting :: silicon.valley, ca
http://www.roadkill.com/~wesc/cyberweb/