[Tutor] hypotenuse

Luke Paireepinart rabidpoobear at gmail.com
Fri Mar 14 03:09:20 CET 2008


Robert Childers wrote:
> I am in an early lesson in "A Byte of Python."  Instead of writing a 
> program to find the area of a rectangle I thought it would be useful 
> to write a program to determine the length of the diagonal of a 
> "golden rectangle", which would of course equal the sq root of the sum 
> of the squares of the width and height.  Here is my program:
> >>> height = input ("Height:")
> Height:1
> >>> width = input ("Width:")
> Width:1.618
> >>> int = ((height**2) + (width**2))
> >>> print int
> 3.617924
> >>> hypotenuse * hypotenuse = int
> SyntaxError: can't assign to operator
>  
> I looked ahead in the lesson and could find no mention of square 
> roots.  How do I find the square root of an integer?
There is a library called 'math' with a 'sqrt' function.
To import modules, you use the 'import' command, as:
import math
To import a specific function from a module, you use a different syntax:
from math import sqrt
If you used the first style of import, you'd call the function like this:
x = math.sqrt(2)
With the second style, you'd call the function like this:
x = sqrt(2)

One other note: You named your variable 'int'.
You should avoid naming your variables after keywords, because you will 
run into problems later.
So you shouldn't use the names int, char, for, while, lambda, def, is, 
and, and names like that.
For example:
 >>> int('12345')
12345
 >>> int = 3 * 3
 >>> int('12345')

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    int('12345')
TypeError: 'int' object is not callable


As you can see, naming the variable 'int' kept us from being able to 
call the 'int' function to convert the string into an integer.
HTH,
-Luke


More information about the Tutor mailing list