[Tutor] calculator [using functions]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 28 Aug 2001 10:13:05 -0700 (PDT)

On Tue, 28 Aug 2001, 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

No problem, and don't worry about it.  Congrats on starting to learn

> 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.

I read your program, and it looks ok.  I agree with dman that using
functions will improve your program.  When we make our own functions,
programs usually get easier to read because there's less to read at one
time.  In some sense, functions act like paragraphs on a page.

Since the program gives the user five choices:

>     print "1. circle area"
>     print "2. square area"
>     print "3. rectangle area"
>     print "4. square root"
>     print "5. add numbers"

we can probably make up 5 separate functions to take care of each shape.  
For example, to pull the "circle area" function into a function, we could
do something like this:

def doCircleArea():
    print "would you like to input radius or diameter?"
    print "1. radius"
    print "2. diameter"
    question = input ("> ")
    if question == 1:
        print "what is the radius?"
        radius = input("> ")
        radius = 3.14*radius**2
        print radius
    elif question == 2:
        print "what is the diameter?"
        diameter = input ("> ")
        diameter = diameter/2
        diameter = diameter**2 * 3.14
        print diameter
        print "whoops thats not good"

and we could do the same thing for the other four shapes.  One side
benefit is that we don't need to indent as much, since we pulled the shape
calculations out of the inner while loop.  Another is that when we want to
add additional stuff (maybe to calculate triangle area), it's a lot easier
to see where to add code.

If we use functions, the main program might look like this:

test = 1
print "alright now for some real math"
while test == 1:
    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"
    shape = input("> ")
    if shape == 1:
    elif shape == 2:
    elif shape == 3:
    elif shape == 4:
    elif share == 5:
        print "whoops thats not good"

If you have more questions, please feel free to ask.  Good luck to you!