[Tutor] Is my style OK in this elementary student exercise?

Daniel Woodhouse wodemoneke at gmail.com
Sat Jul 4 17:50:48 CEST 2009


I had a look at your code, and refactored it a bit.  See my modifications at
http://python.pastebin.com/m50acb143 You'll noticed I removed one of your
functions completely (it was unnecessary) and the get_dict() function is not
so heavily nested.

Some ideas:
raw_input returns a string, so we can safely assume its a string. Whether or
not its a valid name for a student is a different matter, and if you wish to
check such things you may wish to look at the regular expression module
(re).  I wouldn't use eval as you did in the case, instead I did this to
check the score is a valid int:
try:
    val = int(val)
except ValueError:
    print 'Invalid score'

ValueError will catch invalid integers and we can ask the user to input
again.  Generally we should only capture Exceptions that we are expecting,
though there are exceptions to this (no pun intended)...
A lot of your code in get_dict() was repeated (basically the same operations
to get the key and the value). You should try to avoid duplication if
possible, either by putting the code in a seperate function, or just
collecting everything at once as I have done.

Regards,
Daniel Woodhouse


On Sat, Jul 4, 2009 at 3:26 PM, Angus Rodgers <angusr at bigfoot.com> wrote:

>
> Fear not, I won't post all my exercises to the Tutor list!  But
> when I seem to be doing something a little elaborate, it seems a
> good idea to ask if I'm doing anything silly.  In this exercise:
>
> <http://python.pastebin.com/d7e245e0f>   (retention: 1 day)
>
> my /conscious/ worries are:
>
>  (i) trapping the exception StandardError may, for all I know,
> be a daft thing to do;
>
>  (ii) I'm not bothering to be consistent in my use of single and
> double string quotes (but I don't know how much difference this
> makes, to readability and/or reliability);
>
> (iii) some of my lines of code extend beyond 79 characters (but
> again, I don't know how much this matters);
>
>  (iv) correlatively with (iii), my indentation perhaps looks a
> little extreme (perhaps suggesting a redesign, I don't know);
>
>  (v) I'm bound to be doing other silly things that I don't even
> know about ("unknown unknowns").
>
> Any comments? (I don't expect the Spanish Inquisition!)
>
> --
> Angus Rodgers
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090704/fd445783/attachment.htm>


More information about the Tutor mailing list