Python break Statement



Python break Statement

Python break statement is used to terminate the current loop and resumes execution at the next statement, just like the traditional break statement in C.

The most common use for Python break statement is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both Python while and for loops.

If you are using nested loops in Python, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.

Syntax of break Statement

The syntax for a break statement in Python is as follows −

break

Flow Diagram of break Statement

Python break statement

Examples of of break Statement

Example 1: Demonstrating Use of Python break Statement

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!")

When the above code is executed, it produces the following result −

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!

Example 2: Checking for a Number in List

The following program demonstrates the use of break in a for loop iterating over a list. User inputs a number, which is searched in the list. If it is found, then the loop terminates with the 'found' message.

no=int(input('any number: '))
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
   if num==no:
      print ('number found in list')
      break
else:
   print ('number not found in list')

The above program will produce the following output

any number: 33
number found in list
any number: 5
number not found in list

Example 3: Checking for Prime Number

Note that when the break statement is encountered, Python abandons the remaining statements in the loop, including the else block.

The following example takes advantage of this behaviour to find whether a number is prime or not. By definition, a number is prime if it is not divisible by any other number except 1 and itself.

The following code runs a for loop over numbers from 2 to the desired number-1. If it divisible by any value of looping variable, the number is not prime, hence the program breaks from the loop. If the number is not divisible by any number between 2 and x-1, the else block prints the message that the given number is prime.

num = 37
print ("Number: ", num)
for x in range(2,num):
   if num%x==0:
      print ("{} is not prime".format(num))
      break
else:
   print ("{} is prime".format(num))

Assign different values to num to check if it is a prime number or not.

Number: 37
37 is prime
Number: 49
49 is not prime
Advertisements