Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Ternary Elif

#1
Python Ternary Elif

<div><p class="has-luminous-vivid-amber-background-color has-background"><strong>Summary</strong>: To use an elif branch in the ternary operator, use another ternary operator as the result of the else branch (nested ternary operator). The nested ternary operator <code>x if c0 else y if c1 else z</code> returns <code>x</code> if condition <code>c0</code> is met, else if (elif) condition <code>c1</code> is met, it returns <code>y</code>, else it returns <code>z</code>.</p>
<figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/07/elif-1024x576.jpg" alt="Python Ternary Elif" class="wp-image-10815" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/07/elif-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<p><strong>Problem</strong>: You may have seen the ternary operator <code>x if c else y</code>. Is there a similar ternary operator with an additional elif statement? In pseudocode, you want something like:</p>
<pre class="wp-block-preformatted"><code># Pseudocode</code>
<code>x if c <strong>elif y0</strong> else y1</code></pre>
<p>In other words: <em>What’s the best way of extending the ternary operator to what you may call a “quaternary” operator?</em></p>
<p><strong>Background</strong>: The most basic ternary operator <code>x if c else y</code> consists of three operands <code>x</code>, <code>c</code>, and <code>y</code>. It is an expression with a return value. The ternary operator returns <code>x</code> if the Boolean expression <code>c</code> evaluates to <code>True</code>. Otherwise, if the expression <code>c</code> evaluates to <code>False</code>, the ternary operator returns the alternative <code>y</code>.</p>
<p><strong><em><a href="https://blog.finxter.com/python-one-line-ternary/" target="_blank" rel="noreferrer noopener" title="Python One Line Ternary">Learn more about the ternary operator in our detailed blog article!</a></em></strong></p>
<p><strong>Example</strong>: Say, you want to write the following if-then-else condition in a single line of code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> x = 42
>>> if x > 42:
>>> print("no")
>>> elif x == 42:
>>> print("yes")
>>> else:
>>> print("maybe")
yes</pre>
<p>The elif branch wins: you print the output <code>"yes"</code> to the shell. </p>
<p>But how to do it in a single line of code? Just use the ternary operator with an elif statement won’t work (it’ll throw a syntax error):</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/07/image-4.png" alt="" class="wp-image-10807" srcset="https://blog.finxter.com/wp-content/uploads/2020/07/image-4.png 724w, https://blog.finxter.com/wp-content/uplo...300x36.png 300w" sizes="(max-width: 724px) 100vw, 724px" /></figure>
<h2>Method: Nested Ternary Operator</h2>
<p>The answer is simple: nest two ternary operators like so:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> print("no") if x > 42 else print("yes") if x == 42 else print("maybe")
yes</pre>
<p>If the value x is larger than 42, we print “no” to the shell. Otherwise, we execute the remainder of the code (which is a ternary operator by itself). If the value x is equal to 42, we print “yes”, otherwise “maybe”.</p>
<p>So by nesting multiple ternary operators, we can greatly increase our Python one-liner power!</p>
<p><strong>Try it yourself:</strong></p>
<p> <iframe src="https://trinket.io/embed/python/a19986f70c" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p>
<p><em><strong>Exercise</strong>: Which method is more concise? Count the number of characters (or write a small script that does it for you ;))!</em></p>
<h2>Python Ternary Multiple Elif</h2>
<p>In the previous example, you’ve seen how a nested ternary operator semantically adds an elif branch. In theory, you can add an arbitrary number of elif branches by nesting more and more ternary operators:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Method 1: If ... Elif ... Else
x = 42
if x > 42: y = 1
elif x == 42: y = 2
elif x == 12: y = 3
else: y = 4
print(y)
# 2 # Method 2: Nested Ternary Operator
y = 1 if x > 42 else 2 if x == 42 else 3 if x == 12 else 4
print(y)
# 2
</pre>
<p>However, readability suffers badly and you shouldn’t do anything of the sort. A simple mult-line <code>if ... elif ... elif ... else</code> statement is better! </p>
<h2>Discussion</h2>
<p>However, even if the nested ternary operator is more concise than an if-elif-else statement, it’s not recommended because of readability of your code. Most programmers don’t have any trouble understanding a simple if-elif-else statement. But a nested ternary operator is an advanced-level piece of Python code and especially beginners will struggle understanding it. </p>
<p><strong>So, it’s great that you’ve expanded your One-Liner Superpower. But you should use it wisely!</strong></p>
<h2>Related Video: If-Then-Else in One Line of Python Code</h2>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="If-Then-Else in One Line Python" width="1400" height="788" src="https://www.youtube.com/embed/ZGUAaQiO06Y?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Python One-Liners Book</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<figure class="wp-block-image size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
<p><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noreferrer noopener" title="https://www.amazon.com/gp/product/B07ZY7XMX8"><em>Python One-Liners</em> </a>will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:</p>
<p><strong>•</strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br /><strong>•</strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br /><strong>•</strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br /><strong>•</strong>&nbsp;&nbsp;Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators<br /><strong>•</strong>&nbsp;&nbsp;Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting</p>
<p>By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<p><strong><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noreferrer noopener" title="https://www.amazon.com/gp/product/B07ZY7XMX8"><em>Get your Python One-Liners Now!!</em></a></strong></p>
</div>


https://www.sickgaming.net/blog/2020/07/...nary-elif/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016