[Tutor] What is wrong my code?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Mar 25 01:22:52 CET 2006


> I did like your comments about input and raw_input.
> What about if I use on my program:
>
> leg1 = int( raw_input('Enter the first leg of the
> triangle: ') )
> leg2= int( raw_input('Enter the second leg of the
> triangle: ') )
>
> What do you think? This is better/safer, right?

Hi Hoffmann,

Yes, this works fine.

There's a little bit of copy-and-paste here that we can improve: we can
write a helper function to handle the raw_input() andint() conversion
stuff:

######
def read_number(prompt):
    """prompts the user for numeric input, and returns a number."""
    # ...
######

By doing this, we isolate the weirdness of calling int(raw_input(...)) to
a single place, and throughout the rest of our program, we can use our new
helper function read_number().


Concretely: if we had such a function, then we can say:

######
leg1 = read_number('Enter the first leg of the triangle: ')
leg2 = read_number('Enter the second leg of the triangle: ')
######

When we program a bit more, we start to accumulate a bunch of helper
functions to deal with the little details.  Don't be afraid to make such
helper functions whenever you're about to copy-and-paste.


(Doing this also makes certain improvements more easy to do.  For example,
one possible thing you might like to try, once you learn a little more
Python, is to improve read_number() so it persists on asking for a number
until the noncommittal user gives a good number!  *grin*)



More information about the Tutor mailing list