[Tutor] Re: What am I missing??

Bill Bell bill-bell@bill-bell.hamilton.on.ca
Mon, 11 Jun 2001 20:39:39 -0400


DavidCraig@PIA.CA.GOV	wrote, in part:
> I am working through the python tutorial on "How to think like a
> Computer Scientist in Python".
> 
> I know its simple but I can't find why this does not work.  This is
> the distance() I have written.  Below is the error message I get.
> 
> # distance function
> 
> def distance(x1, y1, x2, y2):
>     dx = x2 - x1
>     dy = y2 - y1
>     dsquared = dx**2 + dy**2
>     result = sqrt(dsquared)
>     return result
>   <SNIP>
>     distance(1, 2, 4, 6)
> NameError: name 'distance' is not defined

I'd expect the lines showing your definition of the the function to 
appear more like the following.

>>> def distance(x1, y1, x2, y2):
... 	dx=x2-x1 	
... 	dy=y2-y1 	
... 	dsquared=dx**2+dy**2
... 	result=math.sqrt(dsquared) 	
... 	return result
... 

Note the little dots that appear at the beginning of eachof the lines 
other than the first. The fact that it doesn't suggests that you 
haven't entered the lines of code one at a time so that the Python 
interpreter can handle indentation properly. In any case, if you 
enter the 'def' line, press 'Enter' then enter the next line and press 
'Enter' and so on then the interpreter will cope and your definition 
should work--almost (see below).

When you enter your invokation line you should see a result like 
the following.

>>> distance(1,2,4,6)
5.0

The other thing I notice (because I tripped over it myself) is that you 
use an unadorned 'import' statement to gain access to the sqrt 
function. As a consequence you will need to refer to it as math.sqrt 
(as shown in my code), rather than just sqrt.

HTH (as people say).

Bill

Bill Bell, Software Developer