×

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 Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

Python SQLite

SQLite It is an RDBMS (Relational Database Management System). It is an embedded, serverless, transactional SQL database engine. It is an open-source application. It is named SQLite because of its lightweight....

3 minutes read.

PyShark in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Python program to sort the array element into ascending order

Python program to sort the array element into ascending order In this example, we'll see how to sort the array elements in ascending order using a Python program. Sorting is a...

2 minutes read.

How To Take Multiple Inputs In Python

In C language, we make use of the scanf() function to obtain the values from the user and store it in the variable. Coming to the Python language, we use the...

5 minutes read.

Python program to find the GCD or HCF

Python program to find the GCD or HCF The largest positive integer that perfectly divides the two numbers is the HCF (Highest Common Factor) or GCD (Greatest Common Deviser). For example,...

5 minutes read.

Struct Module in Python

What is a structure in Python? An entity that holds data in form of a structure is called a data structure. In Python, the data structure includes tuples, lists, dictionaries, and...

4 minutes read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.

Crash Course on Python by Google

There is a new, free Python programming course offered by Google on Coursera. No programming experience is necessary. There are numerous Python courses available, but when you learn that Google is...

5 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

Python pycountry

What is Pycountry? Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations...

4 minutes read.

Python Project Ideas for Advanced Developers

Best Python Project Ideas for Advanced Developers Python is an object-oriented, high-level, interpreted programming language created by a developer known Guido Van Rossum. Python is one of the languages that gathered...

9 minutes read.

Exclusive OR in Python

In Python, the exclusive OR (XOR) operator is represented by the caret symbol (^). It compares each bit of the first operand to the corresponding bit of the second operand,...

3 minutes read.

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data...

4 minutes read.

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.

Isreal() Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Data Class in Python

Introduction In Python 3.7, the dataclass modules are introduced as a practical tool for creating organized classes designed specifically for data storage. These classes contain specific attributes and capabilities to deal...

6 minutes read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.