473,809 Members | 2,740 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 2768
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 #31

Steven D'Aprano wrote:
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']
this makes me "jump" from the list comprehension to the function,
harder to follow than 'in place', especially when the function is
simple, it is not necessary. What is the reason for introducing list
comprehension and then later, generator expression when :

a=[]
for x in range(8):
a.append(descri be(x%2))
return a

and

for x in range(8):
yield describe(x%2)

can do the same thing ?

Doesn't it violate the general idiom that it better has one and only
one way to do certain thing ? I believe part of the reason is that one
doesn't need to "jump" up and down.

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.

Now that is obsession for(and bad use of) one-liner. But picking a bad
example of one liner to rule out its effectiveness and readability is a
stretch I would say.

Nov 22 '05 #32

Steven D'Aprano wrote:
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']
this makes me "jump" from the list comprehension to the function,
harder to follow than 'in place', especially when the function is
simple, it is not necessary. What is the reason for introducing list
comprehension and then later, generator expression when :

a=[]
for x in range(8):
a.append(descri be(x%2))
return a

and

for x in range(8):
yield describe(x%2)

can do the same thing ?

Doesn't it violate the general idiom that it better has one and only
one way to do certain thing ? I believe part of the reason is that one
doesn't need to "jump" up and down.

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.

Now that is obsession for(and bad use of) one-liner. But picking a bad
example of one liner to rule out its effectiveness and readability is a
stretch I would say.

Nov 22 '05 #33

Steven D'Aprano wrote:
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)]

BTW, the continuation is not necessary I believe.

[ x==0 and "zero" or ["","-"][x < 0] + ("even", "odd")[x%2] for x in
range(8) ]

isn't too bad. though I like the C one a bit more(as it doesn't
overload the and/or)

[ x==0 ? "zero" : ["","-"][x < 0] + ("even", "odd")[x%2] for x in
range(8) ]

As it is still a very straight forward flow(from left to right, without
"internal decision split in between").

Nov 22 '05 #34

Steven D'Aprano wrote:
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)]

BTW, the continuation is not necessary I believe.

[ x==0 and "zero" or ["","-"][x < 0] + ("even", "odd")[x%2] for x in
range(8) ]

isn't too bad. though I like the C one a bit more(as it doesn't
overload the and/or)

[ x==0 ? "zero" : ["","-"][x < 0] + ("even", "odd")[x%2] for x in
range(8) ]

As it is still a very straight forward flow(from left to right, without
"internal decision split in between").

Nov 22 '05 #35
> 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


Let me tell you something: I'm not a one-liner coder, but sometimes It
is necesary.
For example:
I need to translate data from a DataField to Another.

def Evaluate(condit ion,truepart,fa lsepart):
if condition:
return truepart
else:
return falsepart

dOldDataFields = {}
dNewDataFields = {}

dNewDataFields = {
'CODE': dOldDataFields['CODEDATA'],
'DATE': dOldDataFields['DATE'],
'CONTACT': Evaluate(dOldDa taFields['CONTACTTYPE']==2,
dOldDataFields['FIRSTCONTACT'], dOldDataFields['SECONDCONTACT'])
}

With this, I created a new dic very easy, saving in
dNewDataFields['CONTACT'] the value of dOldDataFields['FIRSTCONTACT']
or the value of dOldDataFields['SECONDCONTACT'] depending on
dOldDataFields['CONTACTTYPE']. How you do this in a practic way without
the use of one-line code? It is needed! You can't avoid it! Even using
a = [if_false_expr, if_true_expr][predicate] or a function, you'll
always have to use a one-line code (for this purpose, of course).

Daniel

Nov 23 '05 #36

This could be done easier this way:

L = [('odd','even')[n%2] for i in range(8)]

Nov 23 '05 #37

This could be done easier this way:

L = [('even','odd')[n%2] for n in range(8)]

Nov 23 '05 #38

Luis M. Gonzalez wrote:
This could be done easier this way:

L = [('even','odd')[n%2] for n in range(8)]


That is even/odd, his(created to demonstrate the uglies of ternary) has
4 states, zero, -/+ then even/odd.

Nov 23 '05 #39
Daniel Crespo wrote:
Let me tell you something: I'm not a one-liner coder, but sometimes It
is necesary.
For example:
I need to translate data from a DataField to Another.

def Evaluate(condit ion,truepart,fa lsepart):
if condition:
return truepart
else:
return falsepart

dOldDataFields = {}
dNewDataFields = {}

dNewDataFields = {
'CODE': dOldDataFields['CODEDATA'],
'DATE': dOldDataFields['DATE'],
'CONTACT': Evaluate(dOldDa taFields['CONTACTTYPE']==2,
dOldDataFields['FIRSTCONTACT'], dOldDataFields['SECONDCONTACT'])
}

With this, I created a new dic very easy, saving in
dNewDataFields['CONTACT'] the value of dOldDataFields['FIRSTCONTACT']
or the value of dOldDataFields['SECONDCONTACT'] depending on
dOldDataFields['CONTACTTYPE']. How you do this in a practic way without
the use of one-line code? It is needed! You can't avoid it!


if you use less verbose names, you can do the same thing in less than half
the number of characters, without a single oneliner:

def convert(old):

new = dict(
CODE=old['CODEDATA'],
DATE=old['DATE']
)

if old['CONTACTTYPE'] == 2:
new['CONTACT'] = old['FIRSTCONTACT']
else:
new['CONTACT'] = old['SECONDCONTACT']

return new

</F>

Nov 23 '05 #40

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
12727
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
3570
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
1682
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
10637
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...
0
10376
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10379
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
10115
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...
1
7660
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5550
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
5687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3014
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.