×

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 object()

Python object() class The object class in Python is a base for all classes. It returns a new featureless object. Syntax class object Parameter NA Return It returns a new featureless object. Example 1 # Python program explaining # the object()...

1 minute read.

How to Convert Int to String in Python?

Every value we use or store in a variable in Python will have a specific data type. It describes the value's nature; based on that, Python will automatically assign a...

4 minutes read.

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

Python Errors and exceptions

Exceptions and errors are the obstacles a programmer constantly faces while writing a program. Firstly, we need to understand what are errors and exceptions and the difference between these two...

6 minutes read.

Difference between Module and Package in Python

The main difference between the module and the package in Python is that the module can be a simple file in Python that contains the different functions and collection of...

4 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Palindrome program in Python

Palindrome program in python A number or string is said to be a palindrome if we invert the number or string and the string or number remains the same as the...

3 minutes read.

Slicing of a String in Python

In this tutorial, we will learn about slicing of a string in Python. First of all, let us know what String and Slicing is. String String is a group of characters that...

6 minutes read.

How to import numy in python

How to Install NumPy in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.

Python program to perform the arithmetic operation

Python program to perform the arithmetic operation This program will write a code to perform some basic arithmetic operations like addition, subtraction, multiplication, exponent, modulus, and division. Here we first need...

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

Accessing Key-value in Dictionary in Python

A Python word reference is an assortment of key-esteem matches where each key is related to worth. Worth in the key-esteem pair can be a number, a string, a rundown,...

5 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Python Banner

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

3 minutes read.

Python Struct

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

3 minutes read.

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

3 minutes read.

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.