Here is how to break a while loop in Python.

import random

# This loop will run forever unless we break it
while True:
    # Generate a random int between 1 and 10
    random_integer = random.randint(1, 10)
    # Stop the loop if the random int is 5
    if random_integer == 5:

The output will consist of a series of numbers until number 5 is picked by the randint method.


The while True part is the condition. It checks if True is True. That is always the case. John is always John. So the while loop will run eternally unless it encounters a break statement. You could also rewrite the above Python code to this and it would do the same thing:

import random

random_integer = None

while random_integer != 5:
    random_integer = random.randint(1, 10)

This time we directly check the condition using the while-statement instead of the if-statement. This version of the code is shorter, but the previous version offers more flexibility since you can add other elif-else blocks of code inside the while loop if necessary.

Related HowTos
Deploy a web app to Heroku
Schedule a Python script for execution at a specific time every day
Store Python passwords securely on Windows, Mac, and Linux
Do dictionary comprehension
Do list comprehension
Create a virtual environment
Create a new file
Merge two lists
Extract items from two different lists into one list
Check if a text file is empty
Randomly select an item from a list
Generate a random integer
Create a pandas DataFrame from a dictionary
Create a pandas DataFrame from a list
Get the last item of a list
Delete a column from a pandas dataframe
Access a column of a pandas dataframe
Create a class
Make a webpage request
Get the first two characters of a string
Loop through two lists at the same time
Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.

Mailing List

We will keep you Python-motivated if you subscribe below.