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
    #1
    1. Advertising

  2. -- bj0rn Guest

    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
    #2
    1. Advertising

  3. 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
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Matt
    Replies:
    8
    Views:
    53,593
    saravanavsk
    Jan 25, 2010
  2. Nmishra
    Replies:
    3
    Views:
    367
    Default User
    May 24, 2004
  3. Replies:
    18
    Views:
    7,085
    Karl Heinz Buchegger
    Jul 22, 2005
  4. Ranjan
    Replies:
    1
    Views:
    2,759
    Eliyahu Goldin
    Apr 10, 2007
  5. Jase Schick
    Replies:
    11
    Views:
    587
    Geoff
    Aug 5, 2010
Loading...

Share This Page