473,386 Members | 1,715 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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.

Mar 19 '06 #1
11 5844
vo****@gmail.com wrote:
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")


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
Mar 19 '06 #2
vo****@gmail.com wrote:
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.


There will be, in Python 2.5 (final release scheduled for August 2006):
answer = "go ahead" if a=="yes" else "stop"


See:
http://mail.python.org/pipermail/pyt...er/056846.html
http://www.python.org/doc/peps/pep-0308/

--Ben

Mar 19 '06 #3
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

Mar 19 '06 #4
vo****@gmail.com writes:
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.


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_expression,
lambda: iftrue_expression)[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_expression) or iffalse_expression

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.
Mar 19 '06 #5
On 2006-03-19, vo****@gmail.com <vo****@gmail.com> wrote:
I want the equivalent of this:

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


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

--
gr****@visi.com
Grant Edwards

Mar 19 '06 #6
vo****@gmail.com wrote:
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.


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."
Mar 19 '06 #7
vo****@gmail.com wrote:
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.

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





Mar 19 '06 #8
Jeffrey Schwab wrote:
vo****@gmail.com wrote:
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.


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


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
Mar 19 '06 #9
vo****@gmail.com wrote:
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.

How about:

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

This works because:
int("yes" == "yes") 1 int("yes" == "no")

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
Mar 19 '06 #10
Georg Brandl wrote:
Jeffrey Schwab wrote:
vo****@gmail.com wrote:
I want the equivalent of this:

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

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


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.


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.
Mar 19 '06 #11
Ron Adam <rr*@ronadam.com> wrote:
vo****@gmail.com wrote:
I want the equivalent of this:

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

in [a] more compact form:

I sometimes find it useful to do:

answers = {True: "go ahead", False: "stop"}
answer = answers[a == "yes"]


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 -- si***@chiark.greenend.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
Mar 21 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Steven T. Hatton | last post by:
I've made no secret of the fact that I really dislike the C preprocessor in C++. No aspect of the language has caused me more trouble. No aspect of the language has cause more code I've read to be...
134
by: James A. Donald | last post by:
I am contemplating getting into Python, which is used by engineers I admire - google and Bram Cohen, but was horrified to read "no variable or argument declarations are necessary." Surely that...
2
by: Steve Jorgensen | last post by:
To begin with an example... Let's say you were wanting to write code usign early binding to the MSXML library, but then be able to switch between early and late binding at will. Conditional...
6
by: Chris Dunaway | last post by:
Consider this code (.Net 2.0) which uses a nullable type: private void button1_Click(object sender, System.EventArgs e) { DateTime? nullableDate; nullableDate = (condition) ? null :...
8
by: Olov Johansson | last post by:
I just found out that JavaScript 1.5 (I tested this with Firefox 1.0.7 and Konqueror 3.5) has support not only for standard function definitions, function expressions (lambdas) and Function...
44
by: petermichaux | last post by:
Hi, I have been using the following line of code to create an object called "Serious" if it doesn't already exist. if (Serious == null) {var Serious = {};} This works in the scripts I use...
6
by: maxwell | last post by:
I'm trying to use the gpp utility (Gnu points to http://en.nothingisreal.com/wiki/GPP) to do conditional compilation in Python, and I'm running into a problem: the same '#' character introduces...
14
by: subramanian100in | last post by:
Consider the following program: #include <iostream> using namespace std; int main() { int i;
4
by: rocketeer | last post by:
I've a set of Javascript classes that maintain state. For example, gm.js might be: var GroupManager { groups: {} }; Over time I add new groups to the list: GroupManager.groups = myGroup; ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.