{"id":115813,"date":"2020-07-24T07:47:51","date_gmt":"2020-07-24T07:47:51","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=11338"},"modified":"2020-07-24T07:47:51","modified_gmt":"2020-07-24T07:47:51","slug":"python-one-line-while-loop-a-simple-tutorial","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/24\/python-one-line-while-loop-a-simple-tutorial\/","title":{"rendered":"Python One Line While Loop [A Simple Tutorial]"},"content":{"rendered":"<p>Python is powerful &#8212; 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>\n<h2>How to Write a While Loop in a Single Line of Python Code?<\/h2>\n<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>\n<ul>\n<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&#8217;t interfere or your operating system forcefully terminates the execution. <\/li>\n<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>\n<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>\n<\/ul>\n<p> <iframe loading=\"lazy\" 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>\n<p><em><strong>Exercise<\/strong>: Run the code. What do you observe? Try to fix the infinite loop!<\/em><\/p>\n<p>Next, you&#8217;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\ufeff\">better coder<\/a> in the process. <\/p>\n<p><strong>Before we move on, I&#8217;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>\n<p>If you like one-liners, you&#8217;ll LOVE the book. It&#8217;ll teach you everything there is to know about a <strong>single line of Python code.<\/strong> But it&#8217;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>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/02\/image-1.png\" alt=\"\" class=\"wp-image-5969\"\/><\/a><\/figure>\n<\/div>\n<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>\n<p>But enough promo, let&#8217;s dive into the first method&#8212;the profane&#8230;<\/p>\n<h2>Method 1: Single-Statement While Loop One-Liner<\/h2>\n<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>\n<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') '''\nhi\nhi\n... '''<\/pre>\n<p>You can easily get this done by writing the command in a single line of code:<\/p>\n<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\nwhile True: print('hi')<\/pre>\n<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>\n<p><strong>Related Article: <\/strong><em>If you&#8217;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>\n<p>Let&#8217;s explore an alternative Python trick that&#8217;s very popular among Python masters:<\/p>\n<h2>Method 2: Multi-Statement While Loop One-Liner <\/h2>\n<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>&#8220;first execute <code>expression1<\/code>, then execute <code>expression2<\/code>&#8220;<\/em>. <\/p>\n<p>Here&#8217;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>\n<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\nwhile c &lt; 10: print(c); c = c + 1 '''\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9 '''<\/pre>\n<p>This way, you can easily compress &#8220;flat&#8221; 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>\n<p>But what if the loop body is not flat but nested in a hierarchical manner&#8212;how to express those nested while loops in a single line?<\/p>\n<h2>Method 3: Nested Compound Statements While Loop One-Liner<\/h2>\n<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>\n<p>In the previous methods, you&#8217;ve seen simple while loop one-liners with one loop body statement, as well as multiple semicolon-separated loop body statements. <\/p>\n<p><strong>Problem<\/strong>: But what if you want to use a compound statement within a simple while loop&#8212;in a single line of code?<\/p>\n<p><strong>Example<\/strong>: The following statement works just fine:<\/p>\n<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:\nif expression: print('hi')<\/pre>\n<p>You can also add multiple statements like this:<\/p>\n<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:\nif expression: print('hi'); print('ho')<\/pre>\n<p>But you cannot use nested compound statements in a while loop one-liner: <\/p>\n<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:\nwhile expression1: if expression2: print('hi')<\/pre>\n<p>Python throws an error does <em>not<\/em> work because both the <code>while<\/code> and <code>if<\/code> statements are compound.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" 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\/uploads\/2020\/07\/image-30-300x142.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/image-30-150x71.png 150w\" sizes=\"auto, (max-width: 479px) 100vw, 479px\" \/><\/figure>\n<\/div>\n<p>However, there&#8217;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>\n<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\nwhile True: print('yes') if True else print('no')<\/pre>\n<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>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter is-resized\"><img loading=\"lazy\" decoding=\"async\" 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\/uploads\/2020\/07\/elif-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/07\/elif-768x432.jpg 768w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<h2>Related Video: One-Line For Loop<\/h2>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<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>\n<h2>Where to Go From Here<\/h2>\n<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\u2014after all, this is what makes them very productive.<\/p>\n<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\u2019s 100% based on free Python cheat sheets and Python lessons. It\u2019s fun, easy, and you can leave anytime.<\/p>\n<h2>Python One-Liners Book<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<figure class=\"wp-block-image size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" 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\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<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 &#8220;one-liners&#8221;: concise statements of useful functionality packed into a single line of code. You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;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&#8217;ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You&#8217;ll also learn how to:<\/p>\n<p><strong>\u2022<\/strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br \/><strong>\u2022<\/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>\u2022<\/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>\n<p>By the end of the book, you&#8217;ll know how to write Python at its most refined, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<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>\n","protected":false},"excerpt":{"rendered":"<p>Python is powerful &#8212; you can condense many algorithms into a single line of Python code. So the natural question arises: can you write a while loop in a single line of code? This article explores this mission-critical question in all detail. How to Write a While Loop in a Single Line of Python Code? [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-115813","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115813","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=115813"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115813\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=115813"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=115813"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=115813"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}