473,569 Members | 2,991 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 5861
vo****@gmail.co m 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.co m 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.co m 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_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.
Mar 19 '06 #5
On 2006-03-19, vo****@gmail.co m <vo****@gmail.c om> 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.co m 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.co m 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.co m 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.co m 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

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

Similar topics

11
2447
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 difficult to understand. I've described it as GOTO's on steroids, and that's what it is!. One argument against abolishing it it that it is useful...
134
7796
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 means that if I misspell a variable name, my program will mysteriously fail to work with no error message. If you don't declare variables, you...
2
4308
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 compilation is one possibility, but it's not practical. 1. You have to put a precompiler condition block around every Dim and every function...
6
12128
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 : DateTime.Now; } When the condition is false, I want to return null. If true, I want to return the current date/time.
8
5085
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 constructors (these three I knew about), but also conditional function definitions, as described in...
44
3335
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 it but but www.jslint.com is not happy with me.
6
2833
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 Python comments and is used by default to introduce #ifdef etc. lines. Here's an example of what I'm trying to do: #ifdef DEBUG...
14
13035
by: subramanian100in | last post by:
Consider the following program: #include <iostream> using namespace std; int main() { int i;
4
2222
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; If I include another Javascript file that also includes a reference to
0
7703
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7926
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8138
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6287
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5223
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
946
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.