# assign operator as variable ?

Discussion in 'Python' started by s99999999s2003@yahoo.com, Jun 7, 2006.

1. ### Guest

hi
in python is there any way to do this

op = "<"
a = 10
b = 20
if a op b :
print "a is less than b"

??

thanks

, Jun 7, 2006

2. ### -- bj0rnGuest

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

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

Will this work for you?:

import operator
op = operator.lt
a = 10
b = 20
if op(a, b):
print "a is less than b"

-- bj0rn

-- bj0rn, Jun 7, 2006

3. ### Fredrik LundhGuest

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>

Fredrik Lundh, Jun 7, 2006