assign operator as variable ?

Fredrik Lundh fredrik at pythonware.com
Wed Jun 7 02:33:34 EDT 2006


s99999999s2003 at yahoo.com wrote:

> in python is there any way to do this
> 
> op = "<"
> a = 10
> b = 20
> if a op b :
>    print "a is less than b"
> 
> ??

the "operator" module contains functions corresponding to all builtin 
operators:

     import operator

     ops = {
         "==": operator.eq,
         "!=": operator.ne,
         "<>": operator.ne,
         "<": operator.lt,
         "<=": operator.le,
         ">": operator.gt,
         ">": operator.ge
         }

     op = "<"

     a = 10
     b = 20

     if ops[op](a, b):
         print "a is less than b"

</F>




More information about the Python-list mailing list