[Tut] What’s the Difference Between return and break 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] What’s the Difference Between return and break in Python? (/thread-100130.html) |
[Tut] What’s the Difference Between return and break in Python? - xSicKxBot - 10-23-2022 What’s the Difference Between return and break in Python? <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{"align":"left","id":"818828","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","readonly":"","score":"5","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}"> <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: 142.5px;"> <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;"> 5/5 – (1 vote) </div> </div> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: What is the difference between <code>return</code> and <code>break</code>? When to use which?</p> <p>Let’s first look at a short answer before we dive into a simple example to understand the differences and similarities between <code>return</code> and <code>break</code>.</p> <h2>Comparison</h2> <div class="wp-block-image"> <figure class="aligncenter size-large"><img loading="lazy" width="1024" height="682" src="https://blog.finxter.com/wp-content/uploads/2022/10/image-190-1024x682.png" alt="" class="wp-image-818971" srcset="https://blog.finxter.com/wp-content/uploads/2022/10/image-190-1024x682.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/10/image-190-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2022/10/image-190-768x512.png 768w, https://blog.finxter.com/wp-content/uploads/2022/10/image-190.png 1327w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure> </div> <p>Both <code><a href="https://blog.finxter.com/python-return/" data-type="post" data-id="19987" target="_blank" rel="noreferrer noopener">return</a></code> and <code><a href="https://blog.finxter.com/python-cheat-sheet/" data-type="post" data-id="305" target="_blank" rel="noreferrer noopener">break</a></code> are keywords in Python.</p> <ul> <li>The keyword <code>return</code> ends a function and passes a value to the caller.</li> <li>The keyword <code>break</code> ends a loop immediately without doing anything else. It can be used within or outside a function.</li> </ul> <figure class="wp-block-table is-style-stripes"> <table> <thead> <tr> <th><code>return</code></th> <th><code>break</code></th> </tr> </thead> <tbody> <tr> <td>Used to end a function</td> <td>Used to end a <code>for</code> or <code>while</code> loop</td> </tr> <tr> <td>Passes an optional value to the caller of the function (e.g., <code>return 'hello'</code>)</td> <td>Doesn’t pass anything to the “outside”</td> </tr> </tbody> </table> </figure> <p>While they serve a different purpose, i.e., ending a function vs ending a loop, there are some cases where they can be used interchangeably. </p> <h2>Similar Use Cases</h2> <p>The following use case shows why you may have confused both keywords <code>return</code> and <code>break</code>. In both cases, you can use them to end a loop inside a function and return to the outside. </p> <p>Here’s the variant using <code>return</code>:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def f(): for i in range(10): print(i) if i>3: return f() </pre> <p>And here’s the variant using <code>break</code>:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def f(): for i in range(10): print(i) if i>3: break f() </pre> <p>Both code snippets do exactly the same—printing out the first 5 values 0, 1, 2, 3, and 4.</p> <p><strong>Output: </strong></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="">0 1 2 3 4</pre> <p>However, this is where the similarity between those two keywords ends. Let’s dive into a more common use case where they both perform different tasks in the code.</p> <h2>Different Use Cases</h2> <p>The following example uses both keywords <code>break</code> and <code>return</code>. It uses the keyword <code>break</code> to end the loop as soon as the loop variable <code>i</code> is <a href="https://blog.finxter.com/python-greater-than/" data-type="post" data-id="30762" target="_blank" rel="noreferrer noopener">greater than</a> 3. </p> <p>So the line <code><a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">print(i)</a></code> is never executed after variable <code>i</code> reaches the value 4—<a href="https://blog.finxter.com/how-to-stop-a-for-loop-in-python/" data-type="post" data-id="729488" target="_blank" rel="noreferrer noopener">the loop ends</a>.</p> <p>But the function doesn’t end because <code>break</code> only ends the loop and not the function. That’s why the statement <code>print('hi')</code> is still executed, and the return value of the function is <code>42</code> (which we also print in the final line). </p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4,7" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def f(): for i in range(10): if i>3: break print(i) print('hi') return 42 print(f()) </pre> <p><strong>Output:</strong></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="">0 1 2 3 hi 42</pre> <h2>Summary</h2> <p>The keyword <code>return</code> is different and more powerful than the keyword <code>break</code> because it allows you to specify an optional return value. But it can only be used in a function context and <strong><em>not</em></strong> outside a function. </p> <ul> <li>You use the keyword <code>return</code> to give back a value to the caller of the function or terminate the whole function.</li> <li>You use the keyword <code>break</code> to immediately stop a <code>for</code> or <code>while</code> <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="post" data-id="4596" target="_blank">loop</a>.</li> </ul> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Rule</strong>: Only if you want to exit a loop inside a function and this would also exit the whole function, you can use both keywords. In that case, I’d recommend using the keyword <code>return</code> instead of <code>break</code> because it gives you more degrees of freedom, i.e., specifying the return value. Plus, it is more explicit which improves the readability of the code.</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <p>Thanks for reading over the whole tutorial—if you want to keep learning, feel free to join my <a href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278" target="_blank" rel="noreferrer noopener">email academy</a>. 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>Recommended Video</h2> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/whats-the-difference-between-return-and-break-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9nDzD6splRk%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure> </div> https://www.sickgaming.net/blog/2022/10/22/whats-the-difference-between-return-and-break-in-python/ |