Can I use a conditional in a variable declaration?

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

    Can I use a conditional in a variable declaration?

    I've done this in Scheme, but I'm not sure I can in Python.

    I want the equivalent of this:

    if a == "yes":
    answer = "go ahead"
    else:
    answer = "stop"

    in this more compact form:


    a = (if a == "yes": "go ahead": "stop")


    is there such a form in Python? I tried playing around with lambda
    expressions, but I couldn't quite get it to work right.

  • Kent Johnson

    #2
    Re: Can I use a conditional in a variable declaration?

    volcs0@gmail.co m wrote:[color=blue]
    > I want the equivalent of this:
    >
    > if a == "yes":
    > answer = "go ahead"
    > else:
    > answer = "stop"
    >
    > in this more compact form:
    >
    >
    > a = (if a == "yes": "go ahead": "stop")[/color]

    If the value for the 'true' case can never have a boolean value of
    False, you can use this form:

    a = (a == "yes") and "go ahead" or "stop"

    The short-circuit evaluation of 'and' and 'or' give the correct result.
    This will not work correctly because the 'and' will always evaluate to
    "" which is False so the last term will be evaluated and returned:

    a = (a == "yes") and "" or "stop"

    and IMO the extra syntax needed to fix it isn't worth the trouble; just
    spell out the if / else.

    Kent

    Comment

    • Ben Cartwright

      #3
      Re: Can I use a conditional in a variable declaration?

      volcs0@gmail.co m wrote:[color=blue]
      > I've done this in Scheme, but I'm not sure I can in Python.
      >
      > I want the equivalent of this:
      >
      > if a == "yes":
      > answer = "go ahead"
      > else:
      > answer = "stop"
      >
      > in this more compact form:
      >
      >
      > a = (if a == "yes": "go ahead": "stop")
      >
      >
      > is there such a form in Python? I tried playing around with lambda
      > expressions, but I couldn't quite get it to work right.[/color]

      There will be, in Python 2.5 (final release scheduled for August 2006):
      [color=blue][color=green][color=darkred]
      >>> answer = "go ahead" if a=="yes" else "stop"[/color][/color][/color]

      See:

      The official home of the Python Programming Language


      --Ben

      Comment

      • volcs0@gmail.com

        #4
        Re: Can I use a conditional in a variable declaration?

        Kent - Thanks for the quick reply. I tried the and/or trick - it does
        work. But you're right - more trouble than its worth.... So for now, I
        did it "the long way". It looks like (see below), this functionality
        will be added in soon.

        Thanks for the quick help.

        -sam

        Comment

        • Paul Rubin

          #5
          Re: Can I use a conditional in a variable declaration?

          volcs0@gmail.co m writes:[color=blue]
          > a = (if a == "yes": "go ahead": "stop")
          >
          > is there such a form in Python? I tried playing around with lambda
          > expressions, but I couldn't quite get it to work right.[/color]

          This has been the subject of huge debate over the years. The answer
          is Python doesn't currently have it, but it will be added to a coming
          version: See http://www.python.org/doc/peps/pep-0308/

          To do it in the most general way with lambda expressions, use (untested):

          a = (lambda: iffalse_express ion,
          lambda: iftrue_expressi on)[bool(condition)]()

          That makes sure that only one of the target expressions gets evaluated
          (they might have side effects).

          There are various more common idioms like

          a = (condition and iftrue_expressi on) or iffalse_express ion

          which can go wrong and evaluate both expressions. It was a bug caused
          by something like this that led to conditional expressions finally
          being accepted into Python.

          Comment

          • Grant Edwards

            #6
            Re: Can I use a conditional in a variable declaration?

            On 2006-03-19, volcs0@gmail.co m <volcs0@gmail.c om> wrote:
            [color=blue]
            > I want the equivalent of this:
            >
            > if a == "yes":
            > answer = "go ahead"
            > else:
            > answer = "stop"[/color]

            If that's what you want, then write that. ;)

            --
            grante@visi.com
            Grant Edwards

            Comment

            • Jeffrey Schwab

              #7
              Re: Can I use a conditional in a variable declaration?

              volcs0@gmail.co m wrote:
              [color=blue]
              > I want the equivalent of this:
              >
              > if a == "yes":
              > answer = "go ahead"
              > else:
              > answer = "stop"
              >
              > in this more compact form:
              >
              > a = (if a == "yes": "go ahead": "stop")
              >
              > is there such a form in Python? I tried playing around with lambda
              > expressions, but I couldn't quite get it to work right.[/color]

              Rather than lambda, this merits a named function. You only have to
              define it once.

              def mux(s, t, f):
              if s:
              return t
              return f

              def interpret(a):
              answer = mux(a == "yes", "go ahead", "stop")
              print answer

              interpret("yes" ) # Prints "go ahead."
              interpret("no") # Prints "stop."

              Comment

              • Ron Adam

                #8
                Re: Can I use a conditional in a variable declaration?

                volcs0@gmail.co m wrote:[color=blue]
                > I've done this in Scheme, but I'm not sure I can in Python.
                >
                > I want the equivalent of this:
                >
                > if a == "yes":
                > answer = "go ahead"
                > else:
                > answer = "stop"
                >
                > in this more compact form:
                >
                >
                > a = (if a == "yes": "go ahead": "stop")
                >
                >
                > is there such a form in Python? I tried playing around with lambda
                > expressions, but I couldn't quite get it to work right.[/color]


                I sometimes find it useful to do:


                answers = {True: "go ahead", False: "stop"}

                answer = answers[a == "yes"]



                This is also sometimes useful when you want to alternate between two values.

                values = {'a':'b', 'b':'a'} # define outside loop

                while 1:
                v = values[v] # alternate between 'a' and 'b'
                ...

                There are limits to this, both the keys and the values need to be hashable.


                Cheers,
                Ron













                Comment

                • Georg Brandl

                  #9
                  Re: Can I use a conditional in a variable declaration?

                  Jeffrey Schwab wrote:[color=blue]
                  > volcs0@gmail.co m wrote:
                  >[color=green]
                  >> I want the equivalent of this:
                  >>
                  >> if a == "yes":
                  >> answer = "go ahead"
                  >> else:
                  >> answer = "stop"
                  >>
                  >> in this more compact form:
                  >>
                  >> a = (if a == "yes": "go ahead": "stop")
                  >>
                  >> is there such a form in Python? I tried playing around with lambda
                  >> expressions, but I couldn't quite get it to work right.[/color]
                  >
                  > Rather than lambda, this merits a named function. You only have to
                  > define it once.
                  >
                  > def mux(s, t, f):
                  > if s:
                  > return t
                  > return f[/color]

                  But be aware that this is not a complete replacement for a syntactic
                  construct. With that function, Python will always evaluate all three
                  arguments, in contrast to the and/or-form or the Python 2.5 conditional.

                  You can show this with

                  test = mux(False, 1/0, 1)

                  and

                  test = False and 1/0 or 1

                  Georg

                  Comment

                  • andy

                    #10
                    Re: Can I use a conditional in a variable declaration?

                    volcs0@gmail.co m wrote:
                    [color=blue]
                    >I've done this in Scheme, but I'm not sure I can in Python.
                    >
                    >I want the equivalent of this:
                    >
                    >if a == "yes":
                    > answer = "go ahead"
                    >else:
                    > answer = "stop"
                    >
                    >in this more compact form:
                    >
                    >
                    >a = (if a == "yes": "go ahead": "stop")
                    >
                    >
                    >is there such a form in Python? I tried playing around with lambda
                    >expressions, but I couldn't quite get it to work right.
                    >
                    >
                    >[/color]
                    How about:

                    a = ["stop","go ahead"][a == "yes"]

                    This works because:
                    [color=blue][color=green][color=darkred]
                    >>> int("yes" == "yes")[/color][/color][/color]
                    1[color=blue][color=green][color=darkred]
                    >>> int("yes" == "no")[/color][/color][/color]
                    0

                    Taking into account all the previous comments - both the literal list
                    elements are evaluated; there is no short-cirtuiting here. If they're
                    just literals, it's no problem, but if they're (possibly
                    compute-intensive) function calls, it would matter. I find the list
                    evaluation easier to parse than the and/or equation, and in instances
                    where that would be necessary, I will use the longhand if ... else ...
                    structure for readability.

                    hth,
                    -andy

                    Comment

                    • Jeffrey Schwab

                      #11
                      Re: Can I use a conditional in a variable declaration?

                      Georg Brandl wrote:[color=blue]
                      > Jeffrey Schwab wrote:[color=green]
                      >> volcs0@gmail.co m wrote:
                      >>[color=darkred]
                      >>> I want the equivalent of this:
                      >>>
                      >>> if a == "yes":
                      >>> answer = "go ahead"
                      >>> else:
                      >>> answer = "stop"
                      >>>[/color]
                      >> def mux(s, t, f):
                      >> if s:
                      >> return t
                      >> return f[/color]
                      >
                      > But be aware that this is not a complete replacement for a syntactic
                      > construct. With that function, Python will always evaluate all three
                      > arguments, in contrast to the and/or-form or the Python 2.5 conditional.[/color]

                      Absolutely true, and I should have mentioned it. In languages that
                      allow ?: syntax, I rarely rely on its short-circuit effect, but it
                      certainly is a significant difference.

                      Comment

                      • Sion Arrowsmith

                        #12
                        Re: Can I use a conditional in a variable declaration?

                        Ron Adam <rrr@ronadam.co m> wrote:[color=blue]
                        >volcs0@gmail.c om wrote:[color=green]
                        >> I want the equivalent of this:
                        >>
                        >> if a == "yes":
                        >> answer = "go ahead"
                        >> else:
                        >> answer = "stop"
                        >>
                        >> in [a] more compact form:[/color]
                        >I sometimes find it useful to do:
                        >
                        > answers = {True: "go ahead", False: "stop"}
                        > answer = answers[a == "yes"][/color]

                        In this particular case, you can get it even more compact as

                        answer = {"yes": "go ahead"}.get(a, "stop")

                        but that's sacrificing elegance and readability for bytes. When I find
                        myself with code like the OP's, I usually rewrite as:

                        answer = "stop"
                        if a == "yes":
                        answer = "go ahead"

                        --
                        \S -- siona@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
                        ___ | "Frankly I have no feelings towards penguins one way or the other"
                        \X/ | -- Arthur C. Clarke
                        her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

                        Comment

                        Working...