473,799 Members | 3,276 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

the PHP ternary operator equivalent on Python

Hi!

I would like to know how can I do the PHP ternary operator/statement
(... ? ... : ...) in Python...

I want to something like:

a = {'Huge': (quantity>90) ? True : False}

Any suggestions?

Thanks

Daniel

Nov 22 '05
48 2765
The cleanest(IMO) is this :

a = (predicate and [if_true_expr] or [if_false_expr])[0]

This would give you the necessary "short circuit" behaviour no matter
what.

a = predicate and if_true_expr or if_false_expr

works most of the time but should if_true_expr turns out to be 0 or
something like that(python False equvialent), the if_false_expr will
still be executed, that becomes a logic error. an example :
a = int_str is None and None or int(int_str)
a = [if_false_expr, if_true_expr][predicate]

This doesn't have the "short circuit" feature and the order is
reversed(harder to read for people familiar with ternary operator).
Cannot be used in some case. like this :

a = [0, int(int_str)][int_str is not None]

here int(int_str) may cause exception if None is a valid value.

The lambda form suggested by others is another variant of the first one
above where you get the short circuit feature but too complex to read.

I don't understand why people are so aganst ternary operator. It is a
must for list comprehension/generator expression(and I believe the
reason it has finally been approved), if/else block or try/except just
don't work in these situations.

Daniel Crespo wrote:
Hi!

I would like to know how can I do the PHP ternary operator/statement
(... ? ... : ...) in Python...

I want to something like:

a = {'Huge': (quantity>90) ? True : False}

Any suggestions?

Thanks

Daniel


Nov 22 '05 #21
On Fri, 18 Nov 2005 11:17:17 -0800, David Wahler wrote:
Daniel Crespo wrote:
I would like to know how can I do the PHP ternary operator/statement
(... ? ... : ...) in Python...

I want to something like:

a = {'Huge': (quantity>90) ? True : False}


Well, in your example the '>' operator already returns a boolean value
so you can just use it directly. Hoewver, I agree that there are
situations in which a ternary operator would be nice. Unfortunately,
Python doesn't support this directly; the closest approximation I've
found is:
(value_if_false , value_if_true)[boolean_value]


Which doesn't short-circuit: both value_if_false and value_if_true are
evaluated.

WHY WHY WHY the obsession with one-liners? What is wrong with the good old
fashioned way?

if cond:
x = true_value
else:
x = false_value

It is easy to read, easy to understand, only one of true_value and
false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
think that newlines cost money or that ever time you used one God killed a
kitten.


--
Steven.

Nov 22 '05 #22
On Fri, 18 Nov 2005 11:17:17 -0800, David Wahler wrote:
Daniel Crespo wrote:
I would like to know how can I do the PHP ternary operator/statement
(... ? ... : ...) in Python...

I want to something like:

a = {'Huge': (quantity>90) ? True : False}


Well, in your example the '>' operator already returns a boolean value
so you can just use it directly. Hoewver, I agree that there are
situations in which a ternary operator would be nice. Unfortunately,
Python doesn't support this directly; the closest approximation I've
found is:
(value_if_false , value_if_true)[boolean_value]


Which doesn't short-circuit: both value_if_false and value_if_true are
evaluated.

WHY WHY WHY the obsession with one-liners? What is wrong with the good old
fashioned way?

if cond:
x = true_value
else:
x = false_value

It is easy to read, easy to understand, only one of true_value and
false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
think that newlines cost money or that ever time you used one God killed a
kitten.


--
Steven.

Nov 22 '05 #23

Steven D'Aprano wrote:
WHY WHY WHY the obsession with one-liners? What is wrong with the good old
fashioned way?

if cond:
x = true_value
else:
x = false_value

It is easy to read, easy to understand, only one of true_value and
false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
think that newlines cost money or that ever time you used one God killed a
kitten.

How do you put this block into list comprehension or generator
expression ? Why the obsession of these block style ?

Nov 22 '05 #24

Steven D'Aprano wrote:
WHY WHY WHY the obsession with one-liners? What is wrong with the good old
fashioned way?

if cond:
x = true_value
else:
x = false_value

It is easy to read, easy to understand, only one of true_value and
false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
think that newlines cost money or that ever time you used one God killed a
kitten.

How do you put this block into list comprehension or generator
expression ? Why the obsession of these block style ?

Nov 22 '05 #25
In article <11************ *********@g47g2 000cwa.googlegr oups.com>,
"bo****@gmail.c om" <bo****@gmail.c om> wrote:
Steven D'Aprano wrote:
WHY WHY WHY the obsession with one-liners? What is wrong with the good old
fashioned way?

if cond:
x = true_value
else:
x = false_value

It is easy to read, easy to understand, only one of true_value and
false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
think that newlines cost money or that ever time you used one God killed a
kitten.

How do you put this block into list comprehension or generator
expression ? Why the obsession of these block style ?


I think the list comprehensions are going to be the death of readable
python programs.
Nov 22 '05 #26
In article <11************ *********@g47g2 000cwa.googlegr oups.com>,
"bo****@gmail.c om" <bo****@gmail.c om> wrote:
Steven D'Aprano wrote:
WHY WHY WHY the obsession with one-liners? What is wrong with the good old
fashioned way?

if cond:
x = true_value
else:
x = false_value

It is easy to read, easy to understand, only one of true_value and
false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
think that newlines cost money or that ever time you used one God killed a
kitten.

How do you put this block into list comprehension or generator
expression ? Why the obsession of these block style ?


I think the list comprehensions are going to be the death of readable
python programs.
Nov 22 '05 #27

Roy Smith wrote:
I think the list comprehensions are going to be the death of readable
python programs.

Could be, but seems that someone in charge of the language wants
readable python programs to die then as if list comprehension is not
enough, there comes generator expression and now the formal acceptance
of ternary operator.

Nov 22 '05 #28

Roy Smith wrote:
I think the list comprehensions are going to be the death of readable
python programs.

Could be, but seems that someone in charge of the language wants
readable python programs to die then as if list comprehension is not
enough, there comes generator expression and now the formal acceptance
of ternary operator.

Nov 22 '05 #29
On Fri, 18 Nov 2005 21:05:50 -0800, bo****@gmail.co m wrote:

Steven D'Aprano wrote:
WHY WHY WHY the obsession with one-liners? What is wrong with the good old
fashioned way?

if cond:
x = true_value
else:
x = false_value

It is easy to read, easy to understand, only one of true_value and
false_value is evaluated. It isn't a one-liner. Big deal. Anyone would
think that newlines cost money or that ever time you used one God killed a
kitten.

How do you put this block into list comprehension or generator
expression ? Why the obsession of these block style ?


Why do you assume that everything you need for your list comprehension has
to go into a single line? Chances are your list comp already calls
functions, so just create one more for it to use.
py> def describe(cond):
.... if cond:
.... return "odd"
.... else:
.... return "even"
....
py> L = [describe(n % 2) for n in range(8)]
py> L
['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

One major advantage is that this makes it easier to test your function
describe() in isolation, always a good thing.

Another advantage is that the idiom "call a function" is extensible to
more complex problems:

def describe(n):
if n < 0:
return "negative " + describe(-n)
elif n == 0:
return "zero"
elif n % 2:
return "odd"
else:
return "even"

L = [describe(n) for n in range(8)]

if much easier to understand and follow than using ternary expressions:

# obviously untested
L = ["zero" if n == 0 else \
"negative " + ("odd" if n % 2 else "even") if n < 0 else \
"odd" if n % 2 else "even" for n in range(8)]

Yes, I've seen ternary expressions nested three and even four deep.

I find it fascinating to read Guido's reasoning for introducing a ternary
statement. From the PEP here http://www.python.org/peps/pep-0308.html he
links to this comment of his:

[quote]
I think Raymond's example is more properly considered an argument for
adding a conditional expression than for removing the current behavior of
the and/or shortcut operators; had we had a conditional expression, he
wouldn't have tried to use the "x and y or z" syntax that bit him.
[end quote]

Looking back to Raymond's example here:
http://mail.python.org/pipermail/pyt...er/056510.html

[quote]
I propose that in Py3.0, the "and" and "or" operators be simplified to
always return a Boolean value instead of returning the last evaluated
argument.

1) The construct can be error-prone. When an error occurs it can be
invisible to the person who wrote it. I got bitten in published code
that had survived testing and code review:

def real(self):
'Return a vector with the real part of each input element'
# do not convert integer inputs to floats
return self.map(lambda z: type(z)==types. ComplexType and z.real or z)

The code fails silently when z is (0+4i). It took a good while to trace
down a user reported error (when Matlab results disagreed with my matrix
module results) and determine that the real() method contained an error.
Even when traced down, I found it hard to see the error in the code.
Now that I know what to look for, it has not happened again, but I do
always have to stare hard at any "and/or" group to mentally verify each
case.
[end quote]
Dare I suggest that if Raymond wasn't struggling to force the body of his
function real() to be a one-liner, he wouldn't have tried to use the "x
and y or z" syntax that bit him? Brevity is not always a virtue.
--
Steven.

Nov 22 '05 #30

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

Similar topics

6
3836
by: praba kar | last post by:
Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this __________________________________ Yahoo! Messenger
0
318
by: Daniel Crespo | last post by:
Hi! I would like to know how can I do the PHP ternary operator/statement (... ? ... : ...) in Python... I want to something like: a = {'Huge': (quantity>90) ? True : False} Any suggestions?
15
12725
by: Arthur Dent | last post by:
Hi all, im just curious if anyone knows..... With .NET 2, VB didnt happen to get a true ternary operator, did it? Stuck away in a corner somewhere? By ternary, i mean something like C's a?b:c syntax. IIf works in most cases, but in some instances you want to use expressions which may fail if they are evaluated when they arent supposed to be, and it would be nice to have a concise way of writing this instead of using a whole If-Then-Else...
5
3569
by: PerlPhi | last post by:
hi,,, while ago i was wondering why do some programmers rarely uses the ternary operator. wherein it is less typing indeed. i believe in the classic virtue of Perl which is laziness. well let me show you something first before i go to my delimma. codes as follows using Mrs. If Else: #!perl/bin/perl use strict; print "Are you sure you want to quit ('yes' or any key for 'no'): "; chomp($_ = <STDIN>);
7
1681
by: kretik | last post by:
I'm sure this is a popular one, but after Googling for a while I couldn't figure out how to pull this off. Let's say I have this initializer on a class: def __init__(self, **params): I'd like to short-circuit the assignment of class field values passed in this dictionary to something like this:
4
2390
by: raiderdav | last post by:
I understand how the ternary operator (question mark - ?) works in an if/else setting, but what does it mean when used as a type? For instance, I'm trying to add a get/set in some existing code, but the return type doesn't match: Rectangle? m_textArea = null; public Rectangle TextArea { set { m_textArea = value; } get { return m_textArea; }
0
9687
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9541
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10484
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10228
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10027
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6805
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5463
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2938
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.