[Tutor] calculator will not multiply

Andre Engels andreengels at gmail.com
Sun Jan 18 16:49:09 CET 2009


On Sun, Jan 18, 2009 at 4:37 PM, David <david at abbottdavid.com> wrote:
> Everything else works + - / but not *
> why?
> thanks
> -david

It works for me.

However, I do have another issue with your code:

> def compute(arg1, arg2, arg3):
>    if sys.argv[2] == "+":
>        total = add(int(sys.argv[1]), int(sys.argv[3]))
>        print total
>    elif sys.argv[2] == "-":
>        total = sub(int(sys.argv[1]), int(sys.argv[3]))
>        print total
>    elif sys.argv[2] == "/":
>        total = dev(int(sys.argv[1]), int(sys.argv[3]))
>        print total
>    elif sys.argv[2] == "*":
>        total = mul(int(sys.argv[1]), int(sys.argv[3]))
>        print total
>    else:
>        print "oops"

You define this as a function of arg1, arg2 and arg3, but inside the
function you use the 'outer value' of sys.argv[1], sys.argv[2] and
sys.argv[3]. It is very much advisable to use local rather than global
variables inside functions. That way:
* you can re-use the function elsewhere in the program, or even in a
different program
* you can develop the function and the main program semi-independently.

For example, suppose you want to make this part of a larger program,
and change the call "myprogram.py 2 + 3" to "myprogram.py calculate 2
+ 3". In your case, you would have to change all the sys.argv inside
the function. If instead you define the function as:

def compute(arg1, arg2, arg3):
   if sys.arg2 == "+":
       total = add(int(sys.arg1), int(sys.arg3))
       print total
   elif sys.arg2 == "-":
       total = sub(int(sys.arg1), int(sys.arg3))
       print total
   elif sys.arg2 == "/":
       total = dev(int(sys.arg1), int(sys.arg3))
       print total
   elif sys.arg2 == "*":
       total = mul(int(sys.arg1), int(sys.arg3))
       print total
   else:
       print "oops"

this can be implemented without changing the function at all, you just
need to change

compute(sys.argv[1], sys.argv[2], sys.argv[3])

to

if sys.argv[1].equals("compute"):
    compute(sys.argv[2], sys.argv[3], sys.argv[4])

-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list