Sick Gaming
[Tut] Python One Line If Without Else - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] Python One Line If Without Else (/thread-96277.html)



[Tut] Python One Line If Without Else - xSicKxBot - 07-19-2020

Python One Line If Without Else

<div><p><em>Crafting beautiful Python one-liners is as much an art as it is a science. In this tutorial, you’ll learn how to compress an if statement without an else branch into a single line of Python code. </em></p>
<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="Python One Line If Without Else" width="1400" height="788" src="https://www.youtube.com/embed/NgtKSU4s_jY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Problem</strong>: What’s the one-liner equivalent of the simple if statement without an else branch?</p>
<p>Here’s an example:</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="">condition = True if condition: print('hi') # hi</pre>
<p>You may want to (i) print something, (ii) assign a value to a variable, or (iii) append an element to a list if the condition holds.</p>
<p>In this article, I’ll show you four methods of how to accomplish this goal. All four methods are generally applicable—and you can easily customize them to your specific application.</p>
<p>Let’s have a quick overview of the four methods in our interactive code shell:</p>
<p> <iframe src="https://trinket.io/embed/python/02d2d186a2" width="100%" height="500" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Run the code for both <code>True</code> and <code>False</code> conditions. Are all methods semantically equivalent?</em></p>
<h2>Method 1: One-Liner If Statement</h2>
<p>The first is also the most straightforward method: <strong>if you want a one-liner without an else statement, just write the if statement in a single line!</strong> There are many tricks (like using the semicolon) that help you create one-liner statements. But for an if body with only one statement, it’s just as simple as avoiding the line break. </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="">condition = True # Method 1: One-Liner If
if condition: print('hi')
# hi</pre>
<p>This method is perfectly valid and you could see it in practice. Yet, I have to mention that it “violates” the PEP8 standard (<em><a href="https://www.python.org/dev/peps/pep-0008/#other-recommendations" target="_blank" rel="noreferrer noopener" title="https://www.python.org/dev/peps/pep-0008/#other-recommendations">multiple statements in a single line</a></em>). Therefore, you shouldn’t consider this to be Pythonic code (there are worse things under the sun though). </p>
<h2>Method 2: Ternary with Throw-Away Else Branch</h2>
<p>Sure, you can also use the ternary operator:</p>
<figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/07/ternary_general-1024x576.jpg" alt="Python Ternary Operator" class="wp-image-10984" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/07/ternary_general-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/07/ternary_general-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/07/ternary_general-768x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<p>If you need a quick refresher on the ternary operator, <a href="https://blog.finxter.com/python-one-line-ternary/" title="Python One Line Ternary" target="_blank" rel="noreferrer noopener">check out my detailed blog article. </a>The ternary operator is commonly used to conditionally assign values. But you can also throw away the return value by not assigning the result to any variable. In this case, it doesn’t matter if you use <code>None</code> or any other “dummy” return value as the result of the else branch:</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="">condition = True # Method 2: Ternary with Dummy
print('hi') if condition else None
</pre>
<p>It’s readable, short, and concise and I like this (well, I may be a bit biased as author of the book <a href="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener">Python One-Liners</a>). Sure, people will ask why you didn’t write it in multiple lines. But where is the fun there?</p>
<h2>Method 3: Ternary with Default Value for Assignment</h2>
<p>If you need to assign a value conditionally to a variable, but you want to do so without an else branch, you can do the following:</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="">condition = True # Method 3: Ternary with Dummy for Assignment
x = 42 if condition else None
</pre>
<p>If the condition does not hold, the “dummy” value <code>None</code> is assigned to the variable. </p>
<h2>Method 4: Short Circuiting</h2>
<p>This method I like most. It uses a Python optimization called “short circuiting” for Boolean operators: the logical <code>and</code> operator simply returns the second operand if the first is <code>True</code>. There’s no Boolean conversion of the second operand, it’s just returned as is. </p>
<p>If the first operand is <code>False</code>, the second operand is not even evaluated. </p>
<p>You can use this to conditionally execute the if branch <code>print('hi')</code> or any other code function.</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="">condition = True # Method 4: Short circuiting
condition and print('hi')</pre>
<p>There are two options:</p>
<ul>
<li><code>condition == True</code>: As the first operand is <code>True</code>, the second operand is returned. Thus, the statement <code>print('hi')</code> is executed and the string <code>hi</code> appears on the screen. </li>
<li><code>condition == False</code>: As the first operand is <code>False</code>, the second operand is not even evaluated because the result of the logical <code>and</code> operation is <code>False</code> anyway. Thus, the statement <code>print('hi')</code> is never executed.</li>
</ul>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


https://www.sickgaming.net/blog/2020/07/18/python-one-line-if-without-else/