hello, its me again :-)

D-Man dsh8290 at rit.edu
Wed May 23 05:07:27 CEST 2001


On Wed, May 23, 2001 at 01:11:53AM +0000, the_2nd_coming wrote:
| thanks to all who have helped me with this simple little program.
| 
| I have finally gotten rid of all the errors, however, now I am getting a 
| value of none returned.
| 
| the source is :
| ---------------------------------------------------------
| 
| def evaluate(list):
|         num1 = int(list[0])
|         num2 = int(list[2])
|         operator = list[1]
|         
|         if operator == '+':
|                 answer = num1 + num2
|         elif operator == '-':
|                 answer = num1 - num2
|         elif operator == 'X':
|                 answer = num1 * num2
|         elif operator == 'x':
|                 answer = num1 * num2
|         elif operator == '*':
|                 answer = num1 * num2
|         elif operator == '/':
|                 answer = num1 / num2
|         else:
|                 print 'invalid operator'
|         
...
|         print evaluate(list)
...
| now what have I missed?!!

A 'return' statement.  If a function simply ends without returning
anything (no return statement) then it implicitly returns 'None'.  I
think you mean to have

    return answer

At the end of the function.  Also I would change the 'else' clause to
throw an exception instead.


If I may, I will suggest an alternate and more compact implementation :

import operator
ops = {
    '+' : operator.add ,
    '-' : operator.sub ,
    '*' : operator.mul ,
    'X' : operator.mul ,
    'x' : operator.mul ,
    '/' : operator.div ,
}

def evaluate( lst ) :
    if len( lst ) != 3 :
        raise Exception(
            "The list of operands/operators must have length of 3" )

    operand1 = lst[0]
    oper = lst[1]
    operand2 = lst[2]

    if not ops.has_key( oper ) :
        raise Exception( "Invalid operator" )

    return ops[ oper ]( operand1 , operand2 )


The 'operator' module defines functions that behave in the same manner
as the operators.  I put together a dictionary using the string
representation of the operator as the key and the associated operator
function as the value.  In the evaluate function I simply check to see
that the given operator is known (a key in the dictionary).  Then all
I need to do is grab the proper function from the dictionary and call
it.  I really don't care what the operator was -- the dictionary
lookup gave me an object that provides the necessary polymorphism.

In Python functions are firt-class objects so this is possible.  Other
languages (like Java) make this nearly impossible and in languages
like C it is possible (function pointers) but not pretty.

I also recommend changing the signature of the evaluate function -- I
think it would be clearer to have 3 separate arguments for the
operands and operator rather than using a list, but that is just my
opinion.

-D





More information about the Python-list mailing list