Does Python have a ternary conditional operator?

4 751

749

If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?

Devoted

Posted 2008-12-27T08:32:18.533

Reputation: 32 385

87

In the Python 3.0 official documentation referenced in a comment above, this is referred to as "conditional_expressions" and is very cryptically defined. That documentation doesn't even include the term "ternary", so you would be hard-pressed to find it via Google unless you knew exactly what to look for. The version 2 documentation is somewhat more helpful and includes a link to "PEP 308", which includes a lot of interesting historical context related to this question.

– nobar – 2013-01-10T05:57:30.073

1

Though Pythons older than 2.5 are slowly drifting to history, here is a list of old pre-2.5 ternary operator tricks: "Python Idioms", search for the text 'Conditional expression' . Wikipedia is also quite helpful Ж:-)

– ジョージ – 2011-05-26T00:48:06.033

10"ternary" (having three inputs) is a consequential property of this impelmentation, not a defining property of the concept. eg: SQL has case [...] { when ... then ...} [ else ... ] end for a similar effect but not at all ternary. – user313114 – 2014-12-15T21:14:24.040

4also ISO/IEC 9899 (the C programming language standard) section 6.5.15 calls it the "the condtitional operator" – user313114 – 2014-12-15T21:20:22.017

3

Wikipedia covers this thoroughly in the article "?:".

– HelloGoodbye – 2016-06-09T08:11:03.970

A million duplicate answers here, but I'd just like to caution against the overuse of the ternary. One is fine, but multiple rows of ternaries can get really hard to read. – Matthew Purdon – 2017-07-04T23:23:01.053

It is mentioned here https://docs.python.org/3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator, but not mentioned in Python Standard Library

– sdaffa23fdsf – 2018-03-14T04:20:11.083

1

In the years since nobar's comment the conditional expression documentation has been updated to say Conditional expressions (sometimes called a “ternary operator”)...

– Scott Martin – 2018-08-15T13:25:07.217

Although an answer has long been accepted, I encourage the questioner (or whoever knows what the question was referring to) to rephrase 'other language constructs'. It's unclear whether you're talking about other Python constructs or constructs from other languages (although I don't know why you'd ask that). – Shule – 2018-09-04T09:10:42.010

Answers

5 648

Yes, it was added in version 2.5.
The syntax is:

a if condition else b

First condition is evaluated, then either a or b is returned based on the Boolean value of condition
If condition evaluates to True, a is returned, else b is returned.

For example:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

Note that conditionals are an expression, not a statement. This means you can't use assignments or pass or other statements in a conditional:

>>> pass if False else x = 3
  File "<stdin>", line 1
    pass if False else x = 3
          ^
SyntaxError: invalid syntax

In such a case, you have to use a normal if statement instead of a conditional.


Keep in mind that it's frowned upon by some Pythonistas for several reasons:

  • The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the order).
  • Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
  • Stylistic reasons.

If you're having trouble remembering the order, then remember that if you read it out loud, you (almost) say what you mean. For example, x = 4 if b > 8 else 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9.

Official documentation:

Vinko Vrsalovic

Posted 2008-12-27T08:32:18.533

Reputation: 201 577

171The order may seems strange for coders however f(x) = |x| = x if x &gt; 0 else -x sounds very natural to mathematicians. You may also understand it as do A in most case, except when C then you should do B instead... – yota – 2016-01-25T15:07:08.177

I keep getting an invalid syntax error. If my variable is populated, then it should return true, and thus perform the statement. print("OK") if status else print("NOT OK") fails at the if. – Pred – 2016-02-22T22:27:51.210

All's fine and dandy but aligning this guy can be tough. Compare to condition\n\t? expression1\n\t: expression2. – rr- – 2016-03-03T22:55:43.433

67Be careful with order of operations when using this. For example, the line z = 3 + x if x &lt; y else y. If x=2 and y=1, you might expect that to yield 4, but it would actually yield 1. z = 3 + (x if x &gt; y else y) is the correct usage. – Kal Zekdor – 2016-03-06T09:23:11.640

4The point was if you want to perform additional evaluations after the conditional is evaluated, like adding a value to the result, you'll either need to add the additional expression to both sides (z = 3 + x if x &lt; y else 3 + y), or group the conditional (z = 3 + (x if x &lt; y else y) or z = (x if x &lt; y else y) + 3) – Kal Zekdor – 2016-04-15T00:36:05.883

2@Pred That fails in Python 2 without from __future__ import print_function because print is a statement, not a function. – chepner – 2016-04-30T17:35:28.117

If using this in the construction of strings then beware 'a' + 'b' if x else 'c' will give either 'ab' or 'c', never 'ac' so bracket accordingly. – Llwyd – 2016-06-01T13:17:51.233

6@Pred try print("OK" if status else "NOT OK") – AdrienW – 2016-08-02T13:21:01.273

@nullgraph Really? I get "dog", not foo("dog"). foo("cat") if False else foo("dog") works for me. As does foo("cat") if False else bar("dog") – Graham Jones – 2016-11-05T21:26:37.580

19I love the vague irony of this syntactic ordering being described as natural by someone called @yota. – nickf – 2016-12-20T21:25:26.937

1what if there are multiple conditions ? – Mr Geek – 2017-05-26T15:31:44.113

@MrGeek, you could group the boolean expressions. "foo" if (bool or bool && bool or etc) else "bar" – Dimesio – 2017-08-09T06:08:33.527

@Dimesio I meant something like if (c1) a1 elif (c2) a2 elif ... else a(n). – Mr Geek – 2017-08-09T09:17:55.163

2@MrGeek, I see what you mean, so you would basically be nesting the operations: "foo" if Bool else ("bar" if Bool else "foobar") – Dimesio – 2017-08-11T00:04:32.330

1@yota perhaps you mean: do A in most case, except when not B then you should do C instead (reflecting both ordering and intent of the construct). Now you realize how so not intuitive this gets. – Hendy Irawan – 2017-08-25T08:39:50.947

@Hendy Irawan we can construct a natural language phrasing for this that's both precise & intuitive though: Do thing X as long as the normal check comes up OK; if it's not coming up OK, then go to the backup plan &amp; do thing Y – Nathan Smith – 2017-10-08T11:06:21.347

1@NathanSmith I'm pretty sure that's non-intuitive. Imagine in the real world when someone says: "Go left... if you're male. But otherwise go right." Compared to: "If you're male, then go left. Otherwise, go right." The only scenarios where I think the Python ternary can be "natural" is for the exact scenario you mentioned, i.e. the check is an "OK check" and the "else" is a throw Exception. But ternary can be used for many other things, math checks, even nested, then this syntax gets really confusing. – Hendy Irawan – 2017-10-08T14:43:58.150

@Hendy Irawan Agreed that the python ternary operator is confusing when overused/used inappropriately. And it can be nested to create obfuscated one-liners. But we seem to agree that there's at least one case where it's pretty natural, so it seems like problems can be avoided if we only use it in these specific scenarios where it's natural. – Nathan Smith – 2017-10-09T19:09:47.887

Compared to Ruby's true if true and true unless true this isn't that confusing. It's kind of silly to force styles in Python because other languages do it differently (admittedly, it might make sense for a certain company or team, which is what style guides are for). If Python were exactly the same as C++, there would be no point in having Python. – Dan Bechard – 2017-11-21T22:02:23.317

a if b if c if d else e else f if x if y else z else b if x else y ... – Yakk - Adam Nevraumont – 2018-01-26T18:37:39.433

wouldnt it be better to use it as : (false_result, truth_result)[ condition ] – Kenstars – 2018-04-12T11:58:02.607

@yota That's well and good, but we're programmers, not, in the main, mathematicians. Face it, it was a boneheaded decision. – Tyson Jacobs – 2018-05-23T22:36:19.063

Programmers need precise correct formulation even more than mathematician, because in mathematics there is always a resort to underlying concepts. A convincing argument is the % operator, mimicking the way "mod" is used in math would have been a disaster. So no, I don't accept your argument. It is like adhering to imperial units. Groetjes Albert – Albert van der Horst – 2018-06-17T12:50:52.090

@Pred You might want to realize that this returns a value: e.g. name="Sally" if gender=="female" else: "John". So, something is assigned to name. A print statement doesn't return anything in Python 2.x; in Python 3.x it returns None. – Shule – 2018-09-04T09:34:21.257

633

You can index into a tuple:

(falseValue, trueValue)[test]

test needs to return True or False.
It might be safer to always implement it as:

(falseValue, trueValue)[test == True]

or you can use the built-in bool() to assure a Boolean value:

(falseValue, trueValue)[bool(<expression>)]

Landon Kuhn

Posted 2008-12-27T08:32:18.533

Reputation: 27 919

92(lambda: print("a"), lambda: print("b"))[test==true]() – Dustin Getz – 2012-03-08T19:31:48.573

12It should be noted that what's within the []s can be an arbitrary expression. Also, for safety you can explicitly test for truthiness by writing [bool(&lt;expression&gt;)]. The bool() function has been around since v2.2.1. – martineau – 2012-05-31T18:20:15.627

10This is great for code-golf, not so much for actual code. Although I have gotten so used to it that I do use it sometimes for conciseness when doing something obvious like picking between two string constants. – Claudiu – 2014-12-05T17:52:12.513

Is this idiomatic in python? Seems confusing but maybe its convention – jskulski – 2015-05-28T20:57:14.757

479Note that this one always evaluates everything, whereas the if/else construct only evaluates the winning expression. – SilverbackNet – 2011-02-04T02:25:24.130

Ugly is in the eye of the beholder, and I don't find this ugly at all. It concisely make elegant use of the fact that bool is a subclass of int and that Python indexes are 0-based. Admittedly, it's probably not the most efficient (as @SilverBackNet mentioned, both options are eval'd). However, this works perfectly for deciding between 1 of 2 strings as @Claudiu said - I use it for this all the time. For example: '%d item%s to process!'%(num_items,('','s')[num_items &gt; 1]) or 'Null hypothesis %s be rejected (p-val = %0.4f)'%(("can't",'must')[pval&lt;alpha],pval). – Dr. Drew – 2016-02-19T07:49:50.750

5I've done a similar trick -- only once or twice, but done it -- by indexing into a dictionary with True and False as the keys: {True:trueValue, False:falseValue}[test] I don't know whether this is any less efficient, but it does at least avoid the whole "elegant" vs. "ugly" debate. There's no ambiguity that you're dealing with a boolean rather than an int. – JDM – 2016-03-01T18:43:37.287

Don't do comparisons to booleans with ==. Instead, you should always use is. – wheeler – 2017-03-31T14:45:50.897

This trick may help avoid timing based attacks on algorithms if it always evaluates both possible results and avoids skipping code (an 'if' skips). – Breezer – 2017-11-29T13:59:33.517

264

For versions prior to 2.5, there's the trick:

[expression] and [on_true] or [on_false]

It can give wrong results when on_true has a false boolean value.1
Although it does have the benefit of evaluating expressions left to right, which is clearer in my opinion.

1. Is there an equivalent of C’s ”?:” ternary operator?

James Brady

Posted 2008-12-27T08:32:18.533

Reputation: 17 429

53The remedy is to use (test and [true_value] or [false_value])[0], which avoids this trap. – ThomasH – 2009-10-21T15:33:59.470

3Ternary operator usually executes faster(sometimes by 10-25%). – volcano – 2014-01-13T07:52:08.903

5@volcano Do you have source for me? – OrangeTux – 2014-08-05T12:30:33.637

2

@OrangeTux Here's the disassembled code. Using the method ThomasH suggested would be even slower.

– mbomb007 – 2018-03-19T20:59:54.140

168

expression1 if condition else expression2

>>> a = 1
>>> b = 2
>>> 1 if a > b else -1 
-1
>>> 1 if a > b else -1 if a < b else 0
-1

Simon Zimmermann

Posted 2008-12-27T08:32:18.533

Reputation: 2 680

13What's the difference between this and the top answer? – kennytm – 2010-05-27T07:59:27.773

61This one emphasizes the primary intent of the ternary operator: value selection. It also shows that more than one ternary can be chained together into a single expression. – Roy Tinker – 2010-10-04T21:14:21.780

4@Craig , I agree, but it's also helpful to know what will happen when there are no parentheses. In real code, I too would tend to insert explicit parens. – Jon Coombs – 2014-12-01T21:30:51.103

4Somehow, I'm able to understand this better than the top answer. – Abhishek Divekar – 2018-03-23T05:46:05.363

113

From the documentation:

Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations.

The expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

See PEP 308 for more details about conditional expressions.

New since version 2.5.

Michael Burr

Posted 2008-12-27T08:32:18.533

Reputation: 280 137

85

An operator for a conditional expression in Python was added in 2006 as part of Python Enhancement Proposal 308. Its form differ from common ?: operator and it's:

<expression1> if <condition> else <expression2>

which is equivalent to:

if <condition>: <expression1> else: <expression2>

Here is an example:

result = x if a > b else y

Another syntax which can be used (compatible with versions before 2.5):

result = (lambda:y, lambda:x)[a > b]()

where operands are lazily evaluated.

Another way is by indexing a tuple (which isn't consistent with the conditional operator of most other languages):

result = (y, x)[a > b]

or explicitly constructed dictionary:

result = {True: x, False: y}[a > b]

Another (less reliable), but simpler method is to use and and or operators:

result = (a > b) and x or y

however this won't work if x would be False.

A possible workaround is to make x and y lists or tuples as in the following:

result = ((a > b) and [x] or [y])[0]

or:

result = ((a > b) and (x,) or (y,))[0]

If you're working with dictionaries, instead of using a ternary conditional, you can take advantage of get(key, default), for example:

shell = os.environ.get('SHELL', "/bin/sh")

Source: ?: in Python at Wikipedia

kenorb

Posted 2008-12-27T08:32:18.533

Reputation: 63 134

81

@up:

Unfortunately, the

(falseValue, trueValue)[test]

solution doesn't have short-circuit behaviour; thus both falseValue and trueValue are evaluated regardless of the condition. This could be suboptimal or even buggy (i.e. both trueValue and falseValue could be methods and have side-effects).

One solution to this would be

(lambda: falseValue, lambda: trueValue)[test]()

(execution delayed until the winner is known ;)), but it introduces inconsistency between callable and non-callable objects. In addition, it doesn't solve the case when using properties.

And so the story goes - choosing between 3 mentioned solutions is a trade-off between having the short-circuit feature, using at least python 2.5 (IMHO not a problem anymore) and not being prone to "trueValue-evaluates-to-false" errors.

gorsky

Posted 2008-12-27T08:32:18.533

Reputation: 1 002

While the tuple of lambdas trick works, it takes roughly 3x as long as the ternary operator. It's only likely to be a reasonable idea if it can replace a long chain of if else if. – Perkins – 2018-10-11T17:34:51.077

51

For Python 2.5 and newer there is a specific syntax:

[on_true] if [cond] else [on_false]

In older Pythons a ternary operator is not implemented but it's possible to simulate it.

cond and on_true or on_false

Though, there is a potential problem, which if cond evaluates to True and on_true evaluates to False then on_false is returned instead of on_true. If you want this behavior the method is OK, otherwise use this:

{True: on_true, False: on_false}[cond is True] # is True, not == True

which can be wrapped by:

def q(cond, on_true, on_false)
    return {True: on_true, False: on_false}[cond is True]

and used this way:

q(cond, on_true, on_false)

It is compatible with all Python versions.

Paolo

Posted 2008-12-27T08:32:18.533

Reputation: 9 821

2The behaviour is not identical - q("blob", on_true, on_false) returns on_false, whereas on_true if cond else on_false returns on_true. A workaround is to replace cond with cond is not None in these cases, although that is not a perfect solution. – None – 2012-09-26T09:09:29.270

4Why not bool(cond) instead of cond is True? The former checks the truthiness of cond, the latter checks for pointer-equality with the True object. As highlighted by @AndrewCecil, "blob" is truthy but it is not True. – Jonas Kölker – 2013-11-11T16:11:06.237

Wow, that looks really hacky! :) Technically, you can even write [on_false, on_True][cond is True] so the expression becomes shorter. – Arseny – 2014-02-24T11:51:08.120

46

Ternary Operator in different programming Languages

Here I just try to show some important difference in ternary operator between a couple of programming languages.

Ternary Operator in Javascript

var a = true ? 1 : 0;
# 1
var b = false ? 1 : 0;
# 0

Ternary Operator in Ruby

a = true ? 1 : 0
# 1
b = false ? 1 : 0
# 0

Ternary operator in Scala

val a = true ? 1 | 0
# 1
val b = false ? 1 | 0
# 0

Ternary operator in R programming

a <- if (TRUE) 1 else 0
# 1
b <- if (FALSE) 1 else 0
# 0

Ternary operator in Python

a = 1 if True else 0
# 1
b = 1 if False else 0
# 0

Now you can see the beauty of python language. its highly readable and maintainable.

Simplans

Posted 2008-12-27T08:32:18.533

Reputation: 1 503

34

You might often find

cond and on_true or on_false

but this lead to problem when on_true == 0

>>> x = 0
>>> print x == 0 and 0 or 1 
1
>>> x = 1
>>> print x == 0 and 0 or 1 
1

where you would expect for a normal ternary operator this result

>>> x = 0
>>> print 0 if x == 0 else 1 
0
>>> x = 1
>>> print 0 if x == 0 else 1 
1

Benoit Bertholon

Posted 2008-12-27T08:32:18.533

Reputation: 21

31

Absolutely, and it is incredibly easy to understand.

general syntax : first_expression if bool_expression_is_true else second_expression

Example: x= 3 if 3 > 2 else 4 
# assigns 3 to x if the boolean expression evaluates to true or 4 if it is false

BattleDrum

Posted 2008-12-27T08:32:18.533

Reputation: 290

4Just not easy to actually use if your project limits line width. :( – weberc2 – 2016-07-28T18:00:42.633

25

Does Python have a ternary conditional operator?

Yes. From the grammar file:

test: or_test ['if' or_test 'else' test] | lambdef

The part of interest is:

or_test ['if' or_test 'else' test]

So, a ternary conditional operation is of the form:

expression1 if expression2 else expression3

expression3 will be lazily evaluated (that is, evaluated only if expression2 is false in a boolean context). And because of the recursive definition, you can chain them indefinitely (though it may considered bad style.)

expression1 if expression2 else expression3 if expression4 else expression5 # and so on

A note on usage:

Note that every if must be followed with an else. People learning list comprehensions and generator expressions may find this to be a difficult lesson to learn - the following will not work, as Python expects a third expression for an else:

[expression1 if expression2 for element in iterable]
#                          ^-- need an else here

which raises a SyntaxError: invalid syntax. So the above is either an incomplete piece of logic (perhaps the user expects a no-op in the false condition) or what may be intended is to use expression2 as a filter - notes that the following is legal Python:

[expression1 for element in iterable if expression2]

expression2 works as a filter for the list comprehension, and is not a ternary conditional operator.

Alternative syntax for a more narrow case:

You may find it somewhat painful to write the following:

expression1 if expression1 else expression2

expression1 will have to be evaluated twice with the above usage. It can limit redundancy if it is simply a local variable. However, a common and performant Pythonic idiom for this use-case is to use or's shortcutting behavior:

expression1 or expression2

which is equivalent in semantics. Note that some style-guides may limit this usage on the grounds of clarity - it does pack a lot of meaning into very little syntax.

Aaron Hall

Posted 2008-12-27T08:32:18.533

Reputation: 163 780

16

Simulating the python ternary operator.

For example

a, b, x, y = 1, 2, 'a greather than b', 'b greater than a'
result = (lambda:y, lambda:x)[a > b]()

output:

'b greater than a'

Sasikiran Vaddi

Posted 2008-12-27T08:32:18.533

Reputation: 484

Why not simply result = (y, x)[a &lt; b] Why do you uses lambda function ? – Grijesh Chauhan – 2013-12-27T05:50:06.320

3@GrijeshChauhan Because on "compliated" expressions, e. g. involving a function call etc., this would be executed in both cases. This might not be wanted. – glglgl – 2014-02-13T08:14:33.413

13

you can do this :-

[condition] and [expression_1] or [expression_2] ;

Example:-

print(number%2 and "odd" or "even")

This would print "odd" if the number is odd or "even" if the number is even.


The result :- If condition is true exp_1 is executed else exp_2 is executed.

Note :- 0 , None , False , emptylist , emptyString evaluates as False. And any data other than 0 evaluates to True.

Here's how it works:

if the condition [condition] becomes "True" then , expression_1 will be evaluated but not expression_2 . If we "and" something with 0 (zero) , the result will always to be fasle .So in the below statement ,

0 and exp

The expression exp won't be evaluated at all since "and" with 0 will always evaluate to zero and there is no need to evaluate the expression . This is how the compiler itself works , in all languages.

In

1 or exp

the expression exp won't be evaluated at all since "or" with 1 will always be 1. So it won't bother to evaluate the expression exp since the result will be 1 anyway . (compiler optimization methods).

But in case of

True and exp1 or exp2

The second expression exp2 won't be evaluated since True and exp1 would be True when exp1 isn't false .

Similarly in

False and exp1 or exp2

The expression exp1 won't be evaluated since False is equivalent to writing 0 and doing "and" with 0 would be 0 itself but after exp1 since "or" is used, it will evaluate the expression exp2 after "or" .


Note:- This kind of branching using "or" and "and" can only be used when the expression_1 doesn't have a Truth value of False (or 0 or None or emptylist [ ] or emptystring ' '.) since if expression_1 becomes False , then the expression_2 will be evaluated because of the presence "or" between exp_1 and exp_2.

In case you still want to make it work for all the cases regardless of what exp_1 and exp_2 truth values are, do this :-

[condition] and ([expression_1] or 1) or [expression_2] ;

Natesh bhat

Posted 2008-12-27T08:32:18.533

Reputation: 2 541

12

Ternary conditional operator simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :

[on_true] if [expression] else [on_false]

1- Simple Method to use ternary operator:

# Program to demonstrate conditional operator
a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print(min)  # Output: 10

2- Direct Method of using tuples, Dictionary, and lambda:

# Python program to demonstrate ternary operator
a, b = 10, 20
# Use tuple for selecting an item
print( (b, a) [a < b] )
# Use Dictionary for selecting an item
print({True: a, False: b} [a < b])
# lamda is more efficient than above two methods
# because in lambda  we are assure that
# only one expression will be evaluated unlike in
# tuple and Dictionary
print((lambda: b, lambda: a)[a < b]()) # in output you should see three 10

3- Ternary operator can be written as nested if-else:

# Python program to demonstrate nested ternary operator
a, b = 10, 20
print ("Both a and b are equal" if a == b else "a is greater than b"
        if a > b else "b is greater than a")

Above approach can be written as:

# Python program to demonstrate nested ternary operator
a, b = 10, 20
if a != b:
    if a > b:
        print("a is greater than b")
    else:
        print("b is greater than a")
else:
    print("Both a and b are equal") 
# Output: b is greater than a

Ali Hallaji

Posted 2008-12-27T08:32:18.533

Reputation: 366

10

In [1]: a = 1 if False else 0

In [2]: a
Out[2]: 0

In [3]: b = 1 if True else 0

In [4]: b
Out[4]: 1

ox.

Posted 2008-12-27T08:32:18.533

Reputation: 1 782

10

More a tip than an answer (don't need to repeat the obvious for the hundreth time), but I sometimes use it as a oneliner shortcut in such constructs:

if conditionX:
    print('yes')
else:
    print('nah')

, becomes:

print('yes') if conditionX else print('nah')

Some (many :) may frown upon it as unpythonic (even, ruby-ish :), but I personally find it more natural - i.e. how you'd express it normally, plus a bit more visually appealing in large blocks of code.

Todor

Posted 2008-12-27T08:32:18.533

Reputation: 5 111

9

Yes, you can use it that way :

is_fat = True
state = "fat" if is_fat else "not fat"

Read more about ternary conditional operator

Daniel Taub

Posted 2008-12-27T08:32:18.533

Reputation: 1 530

4

Yes.

>>> b = (True if 5 > 4 else False)
>>> print b
True

Alejandro Blasco

Posted 2008-12-27T08:32:18.533

Reputation: 540

3

Syntax: The Ternary operator will be given as:

[on_true] if [expression] else [on_false]

e.g

x, y = 25, 50
big = x if x < y else y
print(big)

Saurabh Chandra Patel

Posted 2008-12-27T08:32:18.533

Reputation: 5 491

3

YES, python have a ternary operator, here is the syntax and an example code to demonstrate the same :)

#[On true] if [expression] else[On false]
# if the expression evaluates to true then it will pass On true otherwise On false


a= input("Enter the First Number ")
b= input("Enter the Second Number ")

print("A is Bigger") if a>b else print("B is Bigger")

PythonLover

Posted 2008-12-27T08:32:18.533

Reputation: 56

1

Yes:

Let’s say you want to give variable x some value if some bool is true and likewise

X = 5 if something else x = 10

X = [some value] if [if this is true first value evaluates] else [other value evaluates]

Elad Goldenberg

Posted 2008-12-27T08:32:18.533

Reputation: 54

0

if variable is defined and you want to check if it has value you can just a or b

def test(myvar=None):
    # shorter than: print myvar if myvar else "no Input"
    print myvar or "no Input"

test()
test([])
test(False)
test('hello')
test(['Hello'])
test(True)

will output

no Input
no Input
no Input
hello
['Hello']
True

ewwink

Posted 2008-12-27T08:32:18.533

Reputation: 6 879