assign operator as variable ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • s99999999s2003@yahoo.com

    #1

    assign operator as variable ?

    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

  • -- bj0rn

    #2
    Re: assign operator as variable ?


    s99999999s2003@ yahoo.com wrote:[color=blue]
    > 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"[/color]


    s99999999s2...@ yahoo.com wrote:[color=blue]
    > 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"[/color]

    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

    Comment

    • Fredrik Lundh

      #3
      Re: assign operator as variable ?

      s99999999s2003@ yahoo.com wrote:
      [color=blue]
      > in python is there any way to do this
      >
      > op = "<"
      > a = 10
      > b = 20
      > if a op b :
      > print "a is less than b"
      >
      > ??[/color]

      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>

      Comment

      Working...