473,513 Members | 2,552 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

?: in Python

How can do elegantly in Python:

if condition:
a=1
else:
a=2

like in C:

a=condition?1:2

Dec 14 '05 #1
14 1235
Il 2005-12-14, Andy Leszczynski <ya***@nospam.leszczynscy> ha scritto:
How can do elegantly in Python:

if condition:
a=1
else:
a=2

like in C:

a=condition?1:2


There are tons of threads on this newsgroup and in the python-dev mailing
list about a ternary operator. There's also a PEP AFAIK.

I like this:

In [1]:switch = True

In [2]:a = (1, 2)[switch]

In [3]:print a
2
--
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"
Dec 14 '05 #2
Lawrence Oluyede wrote:
Il 2005-12-14, Andy Leszczynski <ya***@nospam.leszczynscy> ha scritto:
How can do elegantly in Python:

if condition:
a=1
else:
a=2

like in C:

a=condition?1:2

There are tons of threads on this newsgroup and in the python-dev mailing
list about a ternary operator. There's also a PEP AFAIK.

I like this:

In [1]:switch = True

In [2]:a = (1, 2)[switch]

In [3]:print a
2


Like it too, thx. Switch does not have to be bool, so it is more
powerfull than ?:.

A.
Dec 14 '05 #3
On Wed, 14 Dec 2005 21:16:23 +0100, Lawrence Oluyede <ra***@dot.com> wrote:
Il 2005-12-14, Andy Leszczynski <ya***@nospam.leszczynscy> ha scritto:
How can do elegantly in Python:

if condition:
a=1
else:
a=2

like in C:

a=condition?1:2


There are tons of threads on this newsgroup and in the python-dev mailing
list about a ternary operator. There's also a PEP AFAIK.

I like this:

In [1]:switch = True

In [2]:a = (1, 2)[switch]

In [3]:print a
2

You won't like it in a case like
a = (2**20**20, 2)[switch]
or
a = (m/n, sys.maxint)[n==0]
the point is that if/else only evaluates
the expression in one branch, as with C ternary.

You're right, there is a PEP and a ternary expression
coming to python though.

Regards,
Bengt Richter
Dec 14 '05 #4
Andy Leszczynski wrote:
Lawrence Oluyede wrote:
There are tons of threads on this newsgroup and in the python-dev mailing
list about a ternary operator. There's also a PEP AFAIK.

I like this:

In [1]:switch = True

In [2]:a = (1, 2)[switch]

In [3]:print a
2


Like it too, thx. Switch does not have to be bool, so it is more
powerfull than ?:.


Actually, if "switch" is neither bool nor a number that equals 0 or 1,
you'll have trouble... using bool(switch) instead would do what you
thought that did, I guess.

-Peter

Dec 14 '05 #6
On Wed, 14 Dec 2005 14:09:10 -0500, Andy Leszczynski wrote:
How can do elegantly in Python:

if condition:
a=1
else:
a=2

like in C:

a=condition?1:2


I thought you wanted to do it *elegantly*?

Your first solution is perfectly elegant to my eyes, unlike that horrible
C syntax.

--
Steven.

Dec 14 '05 #7

Andy Leszczynski wrote:
How can do elegantly in Python:

if condition:
a=1
else:
a=2

like in C:

a=condition?1:2


a=(condition and [1] or [2])[0]

For this simple snippet, I don't think it is better than if/else, But
you can use it in map/reduce or list comprehension/generator expression.

Dec 14 '05 #8
Steven D'Aprano wrote:
On Wed, 14 Dec 2005 14:09:10 -0500, Andy Leszczynski wrote:

How can do elegantly in Python:

if condition:
a=1
else:
a=2

like in C:

a=condition?1:2

I thought you wanted to do it *elegantly*?

Your first solution is perfectly elegant to my eyes, unlike that horrible
C syntax.


I can tell you what is not elegant in the if else: approach. It is
logically a one operation while you are forced to use varaible "a"
twice. Fundamental flaw IMO.

A.
Dec 15 '05 #9
Andy Leszczynski wrote:
How can do elegantly in Python:

if condition:
a=1
else:
a=2

like in C:

a=condition?1:2


Step (1): Wait for Python 2.5[1]
Step (2): Write the code::

a = 1 if condition else 2

STeVe

[1]http://www.python.org/peps/pep-0308.html
Dec 15 '05 #10
On Wed, 14 Dec 2005 21:16:23 +0100 in comp.lang.python, Lawrence
Oluyede <ra***@dot.com> wrote:
Il 2005-12-14, Andy Leszczynski <ya***@nospam.leszczynscy> ha scritto:
How can do elegantly in Python:

if condition:
a=1
else:
a=2

like in C:

a=condition?1:2


There are tons of threads on this newsgroup and in the python-dev mailing
list about a ternary operator. There's also a PEP AFAIK.

I like this:

In [1]:switch = True

In [2]:a = (1, 2)[switch]

In [3]:print a
2


Note, however, you have the logic backwards. To duplicate the
functionality of the OP's example, you need

a = (2,1)[condition]

or

a = (1,2)[not condition]

Regards,
-=Dave

--
Change is inevitable, progress is not.
Dec 15 '05 #11
On Wed, 14 Dec 2005 20:17:28 -0500, Andy Leszczynski wrote:
I can tell you what is not elegant in the if else: approach. It is
logically a one operation while you are forced to use varaible "a"
twice. Fundamental flaw IMO.


"Logically" one operation?

def twenty_countries_in_seven_days_bus_tour():
...
if today() == Monday:
write_postcode_to_mother("We must be in Belgium.")
else:
get_back_on_the_bus("Not again!")
...
if...else expressions with a single operation are just a special case.
Perhaps a common special case, but still a special case.
--
Steven.

Dec 15 '05 #12
"Andy Leszczynski" <ya***@nospam.leszczynscy> wrote in message
news:pa******************************@comcast.com. ..
How can do elegantly in Python:

if condition:
a=1
else:
a=2


I believe that before long Python will support

a=1 if condition else 2

Dec 16 '05 #13
Andy Leszczynski wrote:
How can do elegantly in Python:

if condition:
a=1
else:
a=2

like in C:

a=condition?1:2


a = condition and A or B
is concise but will fail if A can evaluate as false, e.g.
a = condition and None or 2 # won't do what you want

I tend to use 'condition and A or B' if I'm sure A won't be false, otherwise just write
out the if / else.

Kent
Dec 16 '05 #14
Steven D'Aprano wrote:
On Wed, 14 Dec 2005 20:17:28 -0500, Andy Leszczynski wrote:

I can tell you what is not elegant in the if else: approach. It is
logically a one operation while you are forced to use varaible "a"
twice. Fundamental flaw IMO.

"Logically" one operation?

def twenty_countries_in_seven_days_bus_tour():
...
if today() == Monday:
write_postcode_to_mother("We must be in Belgium.")
else:
get_back_on_the_bus("Not again!")
...
if...else expressions with a single operation are just a special case.
Perhaps a common special case, but still a special case.


First:
"Special cases aren't special enough to break the rules.
Although practicality beats purity."
Second, let's look at again:if condition:
a=1
else:
a=2


The primer meaning behind that is that I want to assign something to a.
What I want to assign is secondary issue. I do not like C syntax of ?:
either but I think it is just practical and self-explanatory.

A.
Dec 18 '05 #15

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

Similar topics

0
7270
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
7178
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7397
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
7565
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
7543
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5704
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...
0
3255
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3242
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
817
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.