[Tutor] calculator

dman dsh8290@rit.edu
Tue, 28 Aug 2001 11:23:10 -0400

On Tue, Aug 28, 2001 at 04:58:03AM -0400, melvin2001 wrote:
| well......im 15 years old and i just started messing with python a
| few days ago so obviously im not gonna be very good :op but i wrote
| a little program that does basic calculations and its not done yet i
| add to it just about every day. just wanted to show you guys to see
| what you think maybe help me out a little too.

It looks operational, but I think it is now time for you to study
functions and try breaking this massively long loop and conditional
statement into some smaller, reusable, functions.  A dictionary that
has strings as keys and functions for values is a good way to
implement the "if" you have.  For example,

options = {
    "1" : circle_area ,
    "2" : square_area ,
    "3" : rectangle area ,
    "4" : square root ,
    "5" : add numbers ,

Then you would have the following for your "main" loop :

print "alright now for some real math\n"
while :
    print "please choose an option"
    print "1. circle area"
    print "2. square area"
    print "3. rectangle area"
    print "4. square root"
    print "5. add numbers"

    # use raw_input() instead of input() -- there are various security
    # holes and issues with using input() in a production environment
    # (it is fine for quick-n-dirty testing/prototyping though)
    shape = raw_input("> ")

    # now get the function that handles this operation and let it do
    # the real work, be sure to check for errors first
    if not options.has_key( shape ) :
        print "Error -- %s is not a valid option" % shape
        continue # go on with the next iteration of the loop

    options[ shape ]()

The body of each 'if' block will be moved into a separation function.
If you see code that is repeated in more than one function, come up
with a way to generalize it and make it another function.  Then each
of your shape functions can call that function.  This makes the code
easier to read and maintain.

This reminds me of the programs I first wrote (in GWBASIC) many years
ago.  It is a good start.  If you want some more concrete examples of
how to break that 'if' into separate functions, ask and I (or someone
else) will provide them when I get the time.