Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Stop a For Loop in Python
1
How to Stop a For Loop in Python

Rate this post

Python provides three ways to stop a for loop:

  1. The for loop ends naturally when all elements have been iterated over. After that, Python proceeds with the first statement after the loop construct.

  2. The keyword
    Code:
    break
    terminates a loop immediately. The program proceeds with the first statement after the loop construct.

  3. The keyword
    Code:
    continue
    terminates only the current loop iteration, but not the whole loop. The program proceeds with the first statement in the loop body.

You can see each of these three methods to terminate a for loop in the following graphic:

[Image: image-125-1024x572.png]

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:
for
loop is to deplete the iterator defined in the loop expression
Code:
for <var> in <iterator>
. If the iterator’s
Code:
next()
method doesn’t return a value anymore, the program proceeds with the next statement after the loop construct. This immediately ends the loop.

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()
function:

Code:
s = 'hello world' for c in range(5): print(c, end='') # hello

[Image: 1f449.png] Recommended Tutorial: Iterators, Iterables, and Itertools

Method 2: Keyword “break”

If the program executes a statement with the keyword
Code:
break
, 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
in an if construct to decide dynamically whether a loop should end, or not.

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
in an
Code:
if
condition to accomplish that:

Code:
s = 'hello world' for i in range(10): print(s[i], end='') if i == 5: break # hello

As soon as the
Code:
if
condition evaluates to
Code:
False
, the
Code:
break
statement is executed—the loop ends.

[Image: 1f449.png] Recommended Tutorial: How to End a While Loop?

Method 3: Keyword “continue”

The keyword
Code:
continue
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.

Here’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:
break
or continues with the next iteration using
Code:
continue
.

However, the remaining loop body that actually does something such as printing
Code:
'NEVER EXECUTED'
is, well, 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! [Image: 2935.png]

[Image: CheatSheet-Python-1-Keywords2-1-791x1024.jpg]

You can download it here:

Summary

You’ve learned three ways to terminate a while loop.
  • Method 1: The for loop terminates automatically after all elements have been visited. You can modify the iterator using the
    Code:
    __next__()
    dunder method.

  • Method 2: The keyword
    Code:
    break
    terminates a loop immediately. The program proceeds with the first statement after the loop construct.

  • Method 3: The keyword
    Code:
    continue
    terminates only the current loop iteration, but not the whole loop. The program proceeds with the first statement in the loop body.

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! [Image: 1f642.png]

Programmer Humor

[Image: 2753.png]
Code:
Question: How did the programmer die in the shower? ☠

❗ Answer: They read the shampoo bottle instructions:
Lather. Rinse. Repeat.
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: