Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Write Multiple Statements on a Single Line in Python?

#1
How to Write Multiple Statements on a Single Line in Python?

<div><p><strong>Problem</strong>: Given multiple Python statements. How to write them as a <a href="https://blog.finxter.com/python-one-line-x/" target="_blank" rel="noreferrer noopener" title="Python One Line X">Python One-Liner</a>?</p>
<p><strong>Example</strong>: Consider the following example of four statements in a block with uniform <a href="https://blog.finxter.com/pep-8-hanging-indentation-and-closing-brackets-in-python/" target="_blank" rel="noreferrer noopener" title="PEP 8: Hanging Indentation and Closing Brackets in Python">indentation</a>:</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="">a = 1
b = 2
c = a + b
print©</pre>
<p>Each of the four statements is written in a separate line in a <a href="https://blog.finxter.com/best-python-ide/" target="_blank" rel="noreferrer noopener" title="Best Python IDE and Code Editors [Ultimate Guide]">code editor</a>—this is the normal procedure. However, what if you want to <a href="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener" title="https://pythononeliners.com/">one-linerize</a> those:</p>
<p><strong><em>How to write all four statements in a single line of code?</em></strong></p>
<p><strong>Solution</strong>: The answer is simple if all statements have a uniform indentation and there’s no <a href="https://blog.finxter.com/how-to-write-a-nested-for-loop-in-one-line-python/" target="_blank" rel="noreferrer noopener" title="How to Write a Nested For Loop in One Line Python?">nested block</a>. In this case, you can use the semicolon as a separator between the statements:</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="">a = 1; b = 2; c = a + b; print©</pre>
<p>Let’s do some <a href="https://finxter.com/" target="_blank" rel="noreferrer noopener" title="https://finxter.com/">practice testing</a> to learn and improve your Python skills:</p>
<p> <iframe src="https://trinket.io/embed/python/a8d4624986" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: one-linerize the given code! Run the code and check if the one-liner does the same as the original code!</em></p>
<h2>Indented Block</h2>
<p>While this works beautifully, if all statements are <em>not indented</em>—does it still work if you have an indentation block that starts with the colon <code>:</code> symbol after <a href="https://blog.finxter.com/if-then-else-in-one-line-python/" target="_blank" rel="noreferrer noopener" title="If-Then-Else in One Line Python [Video + Interactive Code Shell]"><code>if</code>, <code>elif</code>, <code>else</code></a>, <code><a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" title="Python One Line For Loop [A Simple Tutorial]">for</a></code>, <code><a href="https://blog.finxter.com/python-one-line-while-loop-a-simple-tutorial/" title="Python One Line While Loop [A Simple Tutorial]">while</a></code>, or <code><a href="https://blog.finxter.com/python-one-line-exception-handling/" title="Python One Line Exception Handling">try/except</a></code> statements?</p>
<p>Here’s an example of such a block:</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="">for i in range(10): c = i ** 2 print ©</pre>
<p>You try the following one-liner using the semicolon as a separator between the two statements in the block</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="">for i in range(10): c = i ** 2; print© '''
0
1
4
9
16
25
36
49
64
81 '''</pre>
<p>This works beautifully and Python understands what you are trying to do. However, if you have nested indentation blocks, this doesn’t work anymore. </p>
<p>Consider the following 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="">for i in range(3): for j in range(3): print(i, j)</pre>
<p>If you write this in a single line, Python throws a syntax error:</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/08/image.png" alt="" class="wp-image-11892" srcset="https://blog.finxter.com/wp-content/uploads/2020/08/image.png 842w, https://blog.finxter.com/wp-content/uplo...00x178.png 300w, https://blog.finxter.com/wp-content/uplo...68x456.png 768w, https://blog.finxter.com/wp-content/uplo...150x89.png 150w" sizes="(max-width: 842px) 100vw, 842px" /></figure>
<p>While you can discuss if this makes sense or not—given that the syntax is not ambiguous here—it doesn’t change the fact: <strong><em>nested block cannot be one-linerized in a straightforward way.</em></strong> But this doesn’t prevent us from doing it, right?</p>
<h2>Nested Indentation Blocks</h2>
<p><a href="https://blog.finxter.com/how-to-execute-multiple-lines-in-a-single-line-python-from-command-line/" title="How to Execute Multiple Lines in a Single Line Python From Command-Line?" target="_blank" rel="noreferrer noopener">Read the following article to learn how to compress multiple lines of code into a single line!</a></p>
<p><strong>Summary</strong>: To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character <code>'\n'</code> and pass the result into the <code>exec(...)</code> function. You can run this script from the outside (command line, shell, terminal) by using the command <code>python -c "exec(...)"</code>.</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="[Don't Do This At Home] How To One-Linerize Every Multi-Line Python Script &amp; Run It From The Shell" width="1400" height="788" src="https://www.youtube.com/embed/zGJgctQEkSU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>This method is very powerful and it allows you to compress any complicated multi-line script in a single line of Python code!</p>
<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://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><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://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners Now!!</em></a></strong></p>
</div>


https://www.sickgaming.net/blog/2020/08/...in-python/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016