How to end while loop python

Python provides three ways to stop a while loop:

  1. The while loop condition is checked once per iteration. If it evaluates to False, the program ends the loop and proceeds with the first statement after the loop construct.
  2. The keyword break terminates a loop immediately. The program proceeds with the first statement after the loop construct.
  3. The keyword 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 while loop in the following graphic:

How to end while loop python
Figure: Terminate a while loop through (a) the loop condition, (b) the break keyword, or (c) the continue keyword.

To exemplify these methods, you’ll learn how to use each of them to accomplish the same thing: remove the first character from a string until only 5 elements remain.

You can also watch my explainer video as you go through the article:

How to Stop a While Loop in Python?

  • Method 1: While Loop Condition
  • Method 2: Keyword “break”
  • Method 3: Keyword “continue”
  • Python Keywords Cheat Sheet
  • Summary
  • Programmer Humor

Method 1: While Loop Condition

The most Pythonic way to end a while loop is to use the while condition that follows immediately after the keyword while and before the colon such as while : . If the condition evaluates to False, the program proceeds with the next statement after the loop construct. This immediately ends the loop.

Here’s an example that shows how the while loop ends as soon as a given string consists of 5 or fewer characters. In each iteration, you reduce the length of the string in variable s by one using string slicing, so the loop will eventually terminate, no matter the initial length of the string.

s = 'hello world'

while len(s) > 5:
    s = s[1:]

print(s)
# world

Method 2: Keyword “break”

If the program executes a statement with the keyword 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 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 an indefinite while loop with a loop condition that is always fulfilled (while True). If you didn’t end the loop prematurely in the loop body, Python would run this code forever.

s = 'hello world'

while True:
    if len(s) > 5:
        s = s[1:]
    else:
        break

print(s)
# world

Fortunately, you add an if construct that contains the break keyword in the else branch. As soon as the if condition evaluates to False, the else branch is executed and the break statement is executed—the loop ends.

Only a string with 5 or fewer characters causes the if condition to evaluate to False, so the loop ends as soon as s holds the string 'world'.

Method 3: Keyword “continue”

The keyword 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:

s = 'hello world'

while len(s) > 5:
    s = s[1:]
    if len(s) > 5:
        continue
    print(s)

# world

You start with the same string 'hello world'. Python checks if the string has more than 5 characters in the while loop condition—which is the case.

Then, it enters the loop body and essentially reduces the length of the string by one. Now, it checks if len(s) > 5 which remains True as long as the string has more than 5 characters. In these cases, the continue statement is executed and Python immediately ends the current iteration and proceeds with the loop condition while len(s) >5.

However, as soon as the string s consists of only 5 characters 'world', the if branch is not executed and the continue statement is skipped. Instead, it prints the string to the shell and checks the loop condition which is not met—and it leaves the loop.

Although the loop body has been run multiple times, the print() statement was executed only once.

👉 Recommended Tutorial: How to End a For Loop?

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! ?

How to end while loop python

You can download it here:

Summary

You’ve learned three ways to terminate a while loop.

Method 1: The while loop condition is checked once per iteration. If it evaluates to False, the program ends the loop and proceeds with the first statement after the loop construct.

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

Method 3: The keyword 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! 🙂

Programmer Humor

Question: How did the programmer die in the shower? ☠️

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

How to end while loop python

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

How do you end a while loop?

To break out of a while loop, you can use the endloop, continue, resume, or return statement. endwhile; If the name is empty, the other statements are not executed in that pass through the loop, and the entire loop is closed.

How do you stop a while loop in a for loop?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

Do you have to end a while loop in Python?

A while loop iterates over a block of statements until the specified condition evaluates to False. At some point, we always want the loop to end. Otherwise, it will run indefinitely, and a programmer never desires that.