×

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 Program to Find the Greatest Among Three Numbers

Python Program to find the greatest among three numbers We have many approaches to get the largest of three numbers, and here we will discuss a few of them. This python...

2 minutes read.

Python Tuple Methods

Python Tuple Methods Python has two built-in methods that are used for tuples. The following are the two methods: Method Description count() The tuple.count() method in Python returns the number of times a...

1 minute read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

Python Virtual Environment

In this tutorial, we will understand Virtual Environment in Python. We will understand the need for a virtual environment and also see how to make use of it in python....

3 minutes read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

Python Set issubset() method

Python Set issubset() method The set.issubset() method in Python returns True if all items in the set exists in the specified set, otherwise it returns False. Syntax set.issubset(set1) Parameter set- This parameter represents the set to check whether...

2 minutes read.

Cx_Oracle Python with Example

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...

6 minutes read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

How to set up a proxy using selenium in python

What is Proxy? A proxy acts as a middleman between user requests and server responses. The main purposes of proxies are to protect user privacy and encapsulate data between various interactive...

3 minutes read.

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice...

6 minutes read.

Python Uses

Python has advanced in recent years to rank among the programming languages that are most often used globally. It is utilized in everything, including machine learning, software testing, and website...

4 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

Python String decode() method

Python String decode() method The string.decode() method decodes the string using the codec registered for encoding. Default encoding is the current default string encoding. It may raise errors to set a different error handling...

1 minute read.

Python Variable Scope with Local & Non-local Examples

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

ER diagram of the Bank Management System in python

What is an ER diagram? The full form of the ER diagram is the Entity Relationship diagram. This diagram is used in database management systems to have a rough idea of...

3 minutes read.