×

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the condition. Loop control statements can be used to do this. Control statements in loops alter the execution sequence. All automatic objects generated in scope are deleted when execution exits that scope. The following control statements are supported by Python.

  • Continue statement
  • Break statement
  • Pass statement

In this article, the main focus will be on break statement.

When an external condition is triggered, the break statement in Python is used to pull the control out of the loop. Inside the loop body is a break statement (generally after if condition).

Python Break Statement

When the loop finishes due to iterable exhaustion (with for) or when the condition becomes false (with while), but not when the loop is ended by a break statement, the else clause is performed. The following loop, which looks for prime numbers, is an example of this:

>>> for n in range(2, 10):

...     for x in range(2, n):

...         if n % x == 0:

...             print(n, 'equals', x, '*', n//x)

...             break

...     else:

...         # loop fell through without finding a factor

...         print(n, 'is a prime number')

Output:

2 is a prime number

3 is a prime number

4 equals 2 * 2

5 is a prime number

6 equals 2 * 3

7 is a prime number

8 equals 2 * 4

9 equals 3 * 3

When used with a loop, the otherwise clause is more similar to the else clause of a try statement than it is to the else clause of if statements: the else clause of a try statement runs when no exception happens, while the else clause of a loop runs when no break occurs.

Let us see a few examples to understand the concept better.

# Python program to

# demonstrate break statement

s = 'JavaTPoint'

# Using for loop

for letter in s:

            print(letter)

            # break the loop as soon it sees 'v'

            # or 't'

            if letter == 'v' or letter == 't':

                        break

print("Out of for loop")

print()


i = 0

# Using while loop

while True:

            print(s[i])


            # break the loop as soon it sees 'v'

            # or 't'

            if s[i] == 'v' or s[i] == 't':

                        break

            i += 1

print("Out of while loop")

Output:

J

a

v

Out of for loop

J

a

v

Out of while loop

Both loops in the preceding example iterate the string 'JavaTPoint,' and when they reach the character 'v' or 't,' the if condition is true, and the flow of execution is taken out of the loop.

Let’s look at one more example to understand the concept in a better way.

#!/usr/bin/python

for letter in 'Python':     # First Example

   if letter == 'h':

      break

   print 'Current Letter :', letter




var = 10                    # Second Example

while var > 0:             

   print 'Current variable value :', var

   var = var -1

   if var == 5:

      break

print "Good bye!"

Here is the output of the code:

Current Letter : P

Current Letter : y

Current Letter : t

Current variable value : 10

Current variable value : 9

Current variable value : 8

Current variable value : 7

Current variable value : 6

Good bye!

Related Topics

Python Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

Introducing modern python computing in simple packages

Python is the language for newly evolving technologies and has become one of the most popular computer languages in the world. Python is used in everything right from a simple...

3 minutes read.

Shallow Copy and Deep Copy in Python

Shallow Copy and Deep Copy in Python In this section, we will learn about the Shallow Copy and Deep Copy in the Python program. But before going through the topic, we...

6 minutes read.

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal We know that the most widely used number system is a decimal system, but the computer only understands binary values. The...

2 minutes read.

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

Python coding platform

Python is a popular general-purpose programming language with many applications. High-level data structures, datatypes, dynamic binding, and many other features make it useful for both designing complex applications and "glue...

6 minutes read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Python any() Function

Python any() Function The any() function in Python returns a boolean value ‘True’ if any element of the iterable is true or if the iterable is empty, else it returns False. Syntax any(iterable) Parameter Iterable: An iterable object (list, tuple, dictionary) Return This...

1 minute read.

Map Syntax in Python

Introduction: In Python, a function called map acts as an iterator, returning a result after each item in an iterable has been subjected to a function (tuple, lists, etc.). When you...

6 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.

Python Interface

When creating an application, it is important to continuously keep track of its changes. As an application grows, sometimes it gets hard to manage its updates and changes. Often, you...

4 minutes read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

How to clear screen in Python?

How to clear screen in python There are times when we execute our program and it results in an unexpected output. The obtained result can contain some kind of garbage values...

4 minutes read.

What is Ipython shell?

IPython is a command shell for computing in multiple programming languages. IPython was developed for python language by Fernando Perez in 2001 as a well-equipped python interpreter that offers shell...

3 minutes read.

Algorithm for Factorial of a number in Python

What is a Factorial Number? In mathematics, the factorial of a positive integer n, denoted by n!. It is the product of all positive integers less than or equal to n. For...

3 minutes read.

How to open a file in python

Opening a File in Python Python is a user-friendly programming language that makes almost every concept easy. It provides many inbuilt functions in its libraries to work with files. Using these...

6 minutes read.

How to create a login page in python

Users can access an application by providing their username and Password or by authenticating with a social media login on the login screen. Python Tkinter Python provides a variety of choices for...

3 minutes read.