![]() |
|
[Tut] How to Stop a For Loop in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://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 Rate this post Python provides three ways to stop a for loop:
You can see each of these three methods to terminate a for loop in the following graphic: ![]() Let’s dive into each of those three approaches next! Method 1: Visit All Elements in Iterator The most natural way to end a Python Code: forCode: for <var> in <iterator>Code: next()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: range()Code: s = 'hello world' for c in range(5): print(c, end='') # hello Recommended Tutorial: Iterators, Iterables, and ItertoolsMethod 2: Keyword “break” If the program executes a statement with the keyword Code: breakCode: breakIn 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: breakCode: ifCode: s = 'hello world' for i in range(10): print(s[i], end='') if i == 5: break # helloAs soon as the Code: ifCode: FalseCode: break Recommended Tutorial: How to End a While Loop?Method 3: Keyword “continue” The keyword Code: continueHere’s an example: Code: for i in range(10): if i == 5: break else: continue print('NEVER EXECUTED')Python iterates over an iterator with 10 elements. However, in each iteration, it either ends the loop using Code: breakCode: continueHowever, the remaining loop body that actually does something such as printing Code: 'NEVER EXECUTED'Python Keywords Cheat Sheet 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! ![]() ![]() You can download it here: Summary You’ve learned three ways to terminate a while loop.
Thanks for reading this tutorial—if you want to boost your Python skills further, I’d recommend you check out my free email academy and download the free Python lessons and cheat sheets here: Join us, it’s fun! ![]() Programmer Humor Code: Question: How did the programmer die in the shower? ☠❗ Answer: They read the shampoo bottle instructions: Lather. Rinse. Repeat. |