Sick Gaming
[Tut] How to Stop a For Loop in Python - 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] How to Stop a For Loop in Python (/thread-100001.html)



[Tut] How to Stop a For Loop in Python - xSicKxBot - 09-29-2022

How to Stop a For Loop in Python

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;729488&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;0&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;0&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;0\/5 - (0 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;0&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<p>Python provides three ways to stop a for loop:</p>
<ol class="has-pale-cyan-blue-background-color has-background">
<li>The for <strong>loop</strong> ends naturally when all elements have been iterated over. After that, Python proceeds with the first statement after the loop construct. </li>
<li>The keyword <code><strong>break</strong></code> terminates a loop immediately. The program proceeds with the first statement after the loop construct.</li>
<li>The keyword <code><strong>continue</strong></code> terminates only the current loop iteration, but not the whole loop. The program proceeds with the first statement in the loop body.</li>
</ol>
<p>You can see each of these three methods to terminate a for loop in the following graphic:</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="572" src="https://blog.finxter.com/wp-content/uploads/2022/09/image-125-1024x572.png" alt="How to Stop a For Loop in Python" class="wp-image-729552" srcset="https://blog.finxter.com/wp-content/uploads/2022/09/image-125-1024x572.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/09/image-125-300x168.png 300w, https://blog.finxter.com/wp-content/uploads/2022/09/image-125-768x429.png 768w, https://blog.finxter.com/wp-content/uploads/2022/09/image-125.png 1105w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<p>Let’s dive into each of those three approaches next!</p>
<h2>Method 1: Visit All Elements in Iterator</h2>
<p class="has-pale-cyan-blue-background-color has-background">The most natural way to end a Python <code>for</code> loop is to deplete the iterator defined in the loop expression <code>for &lt;var> in &lt;iterator></code>. If the iterator’s <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-next/" data-type="post" data-id="17135" target="_blank">next()</a></code> method doesn’t return a value anymore, the program proceeds with the next statement after the loop construct. This immediately ends the loop.</p>
<p>Here’s an example that shows how the for loop ends as soon as all elements have been visited in the iterator returned by the <code><a href="https://blog.finxter.com/python-range-function/" data-type="post" data-id="18290" target="_blank" rel="noreferrer noopener">range()</a></code> function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s = 'hello world' for c in range(5): print(c, end='') # hello</pre>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="URL" data-id="https://blog.finxter.com/iterators-iterables-and-itertools/" target="_blank" rel="noreferrer noopener">Iterators, Iterables, and Itertools</a></p>
<h2>Method 2: Keyword “break”</h2>
<p class="has-pale-cyan-blue-background-color has-background">If the program executes a statement with the keyword <code><strong>break</strong></code>, the loop terminates immediately. No other statement in the loop body is executed and the program proceeds with the first statement after the loop construct. In most cases, you’d use the keyword <code>break</code> in an if construct to decide dynamically whether a loop should end, or not.</p>
<p>In the following example, we create a string with 11 characters and enter a for loop that ends prematurely after five iterations — using the keyword <code>break</code> in an <code>if</code> condition to accomplish that:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="7" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s = 'hello world' for i in range(10): print(s[i], end='') if i == 5: break # hello
</pre>
<p>As soon as the <code>if</code> condition evaluates to <code>False</code>, the <code>break</code> statement is executed—the loop ends.</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/how-to-stop-a-while-loop-in-python/" data-type="post" data-id="29478" target="_blank" rel="noreferrer noopener">How to End a While Loop?</a></p>
<h2>Method 3: Keyword “continue”</h2>
<p class="has-pale-cyan-blue-background-color has-background">The keyword <code><strong>continue</strong></code> terminates only the current loop iteration, but not the whole loop. The program proceeds with the first statement in the loop body. The most common use of continue is to avoid the execution of certain parts of the loop body, constrained by a condition checked in an if construct.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="6" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for i in range(10): if i == 5: break else: continue print('NEVER EXECUTED')</pre>
<p>Python iterates over an <a rel="noreferrer noopener" href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="post" data-id="29507" target="_blank">iterator</a> with 10 elements. However, in each iteration, it either ends the loop using <code>break</code> or continues with the next iteration using <code>continue</code>. </p>
<p>However, the remaining loop body that actually does something such as <a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">printing</a> <code>'NEVER EXECUTED'</code> is, well, never executed.</p>
<h2>Python Keywords Cheat Sheet</h2>
<p>You can learn about the most important Python keywords in this concise cheat sheet—if you’re like me, you love cheat sheets as well! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2935.png" alt="⤵" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/CheatSheet-Python-1-Keywords2-1-791x1024.jpg" alt="Python Cheat Sheet Keywords" class="wp-image-9543" width="500" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/CheatSheet-Python-1-Keywords2-1-scaled.jpg 791w, https://blog.finxter.com/wp-content/uploads/2020/06/CheatSheet-Python-1-Keywords2-1-232x300.jpg 232w, https://blog.finxter.com/wp-content/uploads/2020/06/CheatSheet-Python-1-Keywords2-1-768x994.jpg 768w, https://blog.finxter.com/wp-content/uploads/2020/06/CheatSheet-Python-1-Keywords2-1-1187x1536.jpg 1187w, https://blog.finxter.com/wp-content/uploads/2020/06/CheatSheet-Python-1-Keywords2-1-1583x2048.jpg 1583w" sizes="(max-width: 791px) 100vw, 791px" /></figure>
</div>
<p>You can download it here:</p>
<h2>Summary</h2>
<p>You’ve learned three ways to terminate a while loop.</p>
<ul>
<li><strong>Method 1: </strong>The for loop terminates automatically after all elements have been visited. You can modify the iterator using the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-__next__-magic-method/" data-type="post" data-id="76098" target="_blank">__next__()</a></code> dunder method.</li>
<li><strong>Method 2: </strong>The keyword <code><strong>break</strong></code> terminates a loop immediately. The program proceeds with the first statement after the loop construct.</li>
<li><strong>Method 3: </strong>The keyword <code><strong>continue</strong></code> terminates only the current loop iteration, but not the whole loop. The program proceeds with the first statement in the loop body.</li>
</ul>
<p>Thanks for reading this tutorial—if you want to boost your Python skills further, I’d recommend you check out my <a href="https://blog.finxter.com/email-academy/" target="_blank" rel="noreferrer noopener" title="Email Academy">free email academy</a> and download the free Python lessons and cheat sheets here:</p>
<p>Join us, it’s fun! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Programmer Humor</h2>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2753.png" alt="❓" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <code><strong>Question:</strong> How did the programmer <strong><em>die</em></strong> in the shower? &#x2620;</p>
<p>&#x2757; <strong>Answer</strong>: They read the shampoo bottle instructions: <br /><em><strong>Lather. Rinse. Repeat.</strong></em></code></p>
</div>


https://www.sickgaming.net/blog/2022/09/28/how-to-stop-a-for-loop-in-python/