Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One Line While Loop [A Simple Tutorial]

#1
Python One Line While Loop [A Simple Tutorial]

<div><p>Python is powerful — you can condense many algorithms into a <a href="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener" title="https://pythononeliners.com/">single line of Python code</a>. So the natural question arises: <strong>can you write a while loop in a single line of code</strong>? This article explores this mission-critical question in all detail.</p>
<h2>How to Write a While Loop in a Single Line of Python Code?</h2>
<p>There are three ways of writing a one-liner while <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">loop</a>:</p>
<ul>
<li><strong>Method 1</strong>: If the loop body consists of one statement, write this statement into the same line: <code>while True: print('hi')</code>. This prints the string <code>'hi'</code> to the shell for as long as you don’t interfere or your operating system forcefully terminates the execution. </li>
<li><strong>Method 2: </strong>If the loop body consists of multiple statements, use the semicolon to separate them: <code>while True: print('hi'), print('bye')</code>. This runs the statements one after the other within the while loop. </li>
<li><strong>Method 3</strong>: If the loop body consists nested compound statements, replace the inner compound structures with the ternary operator: <code>while True: print('hi') if condition else print('bye'</code>). </li>
</ul>
<p> <iframe height="400px" width="100%" src="https://repl.it/@finxter/RedUtterOolanguage?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<p><em><strong>Exercise</strong>: Run the code. What do you observe? Try to fix the infinite loop!</em></p>
<p>Next, you’ll dive deep into each of these methods and become a <a href="https://blog.finxter.com/full-time-python-freelancer/" target="_blank" rel="noreferrer noopener" title="How to Go Full-Time ($3000/m) as a Python Freelancer">better coder</a> in the process. </p>
<p><strong>Before we move on, I’m excited to present you my brand-new Python book <a rel="noreferrer noopener" href="https://amzn.to/2WAYeJE" target="_blank" title="https://amzn.to/2WAYeJE">Python One-Liners</a></strong> (Amazon Link).</p>
<p>If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it’s also an <strong>introduction to computer science</strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!</em></strong></p>
<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img src="https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png" alt="" class="wp-image-5969"/></a></figure>
</div>
<p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE">The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).</a></p>
<p>But enough promo, let’s dive into the first method—the profane…</p>
<h2>Method 1: Single-Statement While Loop One-Liner</h2>
<p>Just writing the while loop into a single line of code is the most direct way of accomplishing the task. Say, you want to write the following infinite while loop 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="">while True: print('hi') '''
hi
hi
... '''</pre>
<p>You can easily get this done by writing the command 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=""># Method 1: Single-Line While Loop
while True: print('hi')</pre>
<p>While this answer seems straightforward, the interesting question is: <strong><em>can we write a more complex while loop that has a longer loop body in a single line?</em></strong></p>
<p><strong>Related Article: </strong><em>If you’re interested in compressing whole algorithms into a single line of code, check out <a href="https://blog.finxter.com/10-python-one-liners/">this article with 10 Python one-liners</a> that fit into a single tweet. </em></p>
<p>Let’s explore an alternative Python trick that’s very popular among Python masters:</p>
<h2>Method 2: Multi-Statement While Loop One-Liner </h2>
<p>As it turns out, you can also use the semicolon to separate multiple independent statements and express them in a single line. The statement <code>expression1; expression2</code> reads <em>“first execute <code>expression1</code>, then execute <code>expression2</code>“</em>. </p>
<p>Here’s an example how you can run a while loop until a counter variable <code>c</code> reaches the threshold <code>c == 10</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="">c = 0
while c &lt; 10: print©; c = c + 1 '''
0
1
2
3
4
5
6
7
8
9 '''</pre>
<p>This way, you can easily compress “flat” loop bodies in a single line of <a href="https://blog.finxter.com/python-crash-course/" target="_blank" rel="noreferrer noopener" title="Python Programming Tutorial [+Cheat Sheets]">Python </a>code. </p>
<p>But what if the loop body is not flat but nested in a hierarchical manner—how to express those nested while loops in a single line?</p>
<h2>Method 3: Nested Compound Statements While Loop One-Liner</h2>
<p>You often want to use <a href="https://docs.python.org/3/reference/compound_stmts.html" target="_blank" rel="noreferrer noopener" title="https://docs.python.org/3/reference/compound_stmts.html">compound statements</a> in Python that are statements that require an indented block such as if statements or while loops. </p>
<p>In the previous methods, you’ve seen simple while loop one-liners with one loop body statement, as well as multiple semicolon-separated loop body statements. </p>
<p><strong>Problem</strong>: But what if you want to use a compound statement within a simple while loop—in a single line of code?</p>
<p><strong>Example</strong>: The following statement works just fine:</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=""># YES:
if expression: print('hi')</pre>
<p>You can also add multiple statements like this:</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=""># YES:
if expression: print('hi'); print('ho')</pre>
<p>But you cannot use nested compound statements in a while loop one-liner: </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=""># NO:
while expression1: if expression2: print('hi')</pre>
<p>Python throws an error does <em>not</em> work because both the <code>while</code> and <code>if</code> statements are compound.</p>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/07/image-30.png" alt="Nested Compound Statements Error" class="wp-image-11342" width="479" height="227" srcset="https://blog.finxter.com/wp-content/uploads/2020/07/image-30.png 639w, https://blog.finxter.com/wp-content/uplo...00x142.png 300w, https://blog.finxter.com/wp-content/uplo...150x71.png 150w" sizes="(max-width: 479px) 100vw, 479px" /></figure>
</div>
<p>However, there’s an easy fix to make this work. You can replace the <code>if expression2: print('hi')</code> part with a <a href="https://blog.finxter.com/python-one-line-ternary/" title="Python One Line Ternary" target="_blank" rel="noreferrer noopener">ternary operator</a> and use an expression rather than a compound statement:</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 3: One-Line While Loop + Ternary Operator
while True: print('yes') if True else print('no')</pre>
<p>You can also use <a href="https://blog.finxter.com/python-ternary-elif/" title="Python Ternary Elif" target="_blank" rel="noreferrer noopener">nested ternary operators</a> to account for possibly nested if blocks:</p>
<div class="wp-block-image">
<figure class="aligncenter 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>
</div>
<h2>Related Video: One-Line For Loop</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="Python One Line For Loop [A Simple Tutorial]" width="1400" height="788" src="https://www.youtube.com/embed/M6XNZ40lRFQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" target="_blank" rel="noreferrer noopener" title="Python One Line For Loop [A Simple Tutorial]">You can find out more about the single-line for loop in my detailed article here. </a></p>
<h2>Where to Go From Here</h2>
<p>Knowing small <a href="https://blog.finxter.com/10-python-one-liners/">Python one-liner tricks</a> such as the list comprehension and single-line for loops is vital for your success in the Python language. Every expert coder knows them by heart—after all, this is what makes them very productive.</p>
<p>If you want to learn the language Python by heart, join my <a href="https://blog.finxter.com/subscribe/">free Python email course</a>. It’s 100% based on free Python cheat sheets and Python lessons. It’s fun, easy, and you can leave anytime.</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/07/...-tutorial/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016