assign operator as variable ?

S

s99999999s2003

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
 
B

-- bj0rn

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"


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
 
F

Fredrik Lundh

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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top