1st non-trivial program - gentle criticism requested

Donn Cave donn at u.washington.edu
Thu Apr 13 12:44:14 EDT 2000


Quoth p.agapow at ic.ac.uk (Paul-Michael Agapow):
| I'm experimenting with Python for a number of purposes (an embedded
| language for simulations, a tool for exploring experimental data, a good
| first programming language) and so I've cobbled together my first
| non-trivial program. With some trepidation, I post it here in the hopes
| that experts will be able to coach me in "The Python Way". I realise it
| looks like C++ (my usual langauge), but criticisms of style would be
| useful too.

OK:  It looks too much like C++!  You don't need to end lines with ;.
You don't need to surround expressions with () in an if statement.  It's
not the worst of sins, but you might as well ditch this stuff.

As for the data structures, like "Alex" I would think about more classes
and fewer module globals.  This is not a critical flaw, assuming your
program works, but as a general rule the class is your most adaptable
programming tool and to benefit from it, you have to use it.  As an
exercise, rewrite so the only module level statements are "import",
"class" and "if" (i.e., if __main__...)

That tends towards the other extreme of usage, inasmuch as it is really
very common to use a few module level functions or global constants.
It's just an exercise, not a religious mandate.  In the course of the
exercise, you may find yourself in territory where good usage is
somewhat controversial.  For example, objects other than methods
are legal and fairly common in "class" scope, but there are some
pitfalls to this that worry some people.  Experiment, look for the
properties of an object defined in class scope when seen through
the class instance ("self"), vs. when accessed directly via the class.

There's a builtin max() that I think can do the work of your findMax.

I have plenty of these in my programs:

   print "The alphabet is '" + gAlphabet + "'"

but today I prefer

   print "The alphabet is '%s'" % gAlphabet

because of the greater tolerance for objects that are not really
strings but have string representations.  (OK, it's a string, but
what will happen if you later change this object to something else?)

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list