[Tutor] What is wrong my code?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Mar 24 23:45:25 CET 2006


> #!/usr/bin/python
>
> import math
>
> print '''This program calculates the lenght of the
> hypotenuse of a right triangle
>     given the lenghts of the two legs as
> parameters.\n'''
>
> leg1 = input('Enter the first leg of the triangle: ')
> leg2 = input('Enter the second leg of the triangle: ')


Hi Hoffmann,

Although this works, the use of input() is a little less safe than using
raw_input(), and input gives slightly unhappy error messages on certain
kinds of input.  For example:

######
>>> input("number? ")
number? four
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'four' is not defined
######

That is, certain kinds of input will give us things like NameError.


But here's another example where input() can do funny things:

######
>>> def test():
...     x = input("x?: ")
...     y = input("y?: ")
...     print x, y
...
>>> test()
x?: 3
y?: x
3 3
######

Although this is "cute", it shows that it's also terribly hard to figure
out what's going on with input() sometimes.  *grin*

So because of this, I'd recommend using raw_input() instead: even though
you have to do a little more work to get numbers out of it, it's
ultimately a bit saner and more reliable to use than input().



> def hypotenuse(x, y):
>     result = math.sqrt(x**2 + y**2)
>     return result

There's no need to do the assignment to 'result' here.  We can return the
value straightaway:

#################################
def hypotenuse(x, y):
    return math.sqrt(x**2 + y**2)
#################################



Although it's "obvious", it might also help to add some kind of
documentation string explaining hypotenuse, and what it takes in
and returns.  Something like:

###################################################################
def hypotenuse(x, y):
    """hypotenuse: number number -> number
    hypotenuse() returns the length of the hypotenuse of a right
    triangle with legs of length x and y."""
    # ... rest of function body
###################################################################

might seem like overkill for such a simple function, but the habit is a
good one.


In an ideal world, all functions would have some kind of comment like
that, to communicate the human intent to the reader.  I admit that I often
just hack functions up without saying what they mean... but I do feel
guilty afterwards.  *grin*


I hope this helps!



More information about the Tutor mailing list