Break function in Python

In the previous article we have gone through the various approaches of writing a program to print multiplication tables, now let us explore the break function in Python. Before we explore the concept and usage let us look at a problem. We are required to get the smallest divisor of a number such that the divisor is greater than 1. For example if n is 6, then the smallest divisor of the number greater than 1 is 2. If the number provided is 49, the value to be returned is 49. The smallest divisor of 13 is 13 itself since it is a prime number.

Working with break function in Python

We are required to accept a number as the user-given input. For the input number we want to obtain the smallest divisor which is greater than 1( hence we exclude 1), we begin our loop count at 2. We then check if every increasing number higher than 2 is able to divide n entirely. Since we only need to obtain the 1st value without proceeding further we would need to quit the looping structure as soon as the value is obtained. Such a situation is where the Break function in Python becomes useful.

Let us see what a Python program accounting for all these factors and requirements, looks like:

n=int(input("Enter n:"))
for x in range(2, n+1):
    if n%x==0:
       print(x)
       break
Output:
Enter n:17
17

We see that the loop just returns the value needed and without further attempts breaks the loop immediately. Let us attempt the same kind of program but with while loop rather than for loop.

n=int(input("Enter n:"))
x=2
while x<=n:
    if n%x==0:
       print(x)
       break
   x=x+1
Output:
Enter n:6
2

As soon as the while loop encounters the break statement, it is forced to quit. Let us look at another example before we conclude this article. A question that is quite common during basic interviews.

i=1
While i<=5:
    if i==3:
      break
    print(i)
    i=i+1
print(i)

What would be the resultant output from the above code?

The value of i starts at 1, the loop is allowed to run as long as it meets the condition wherein it is less than or equal to 5, however a second conditional if statement makes the program execute the break function once the value of 3 is reached and then print out the value. As part of the looping structure, the variable count of i is also increased on each run. Outside of the loop, the program still makes the request to print out the value of i at the end.

Output:
1
2
3

Hence we have explored the purpose of the break function in Python, in the next article we will look at another function which is similarly important to manipulating loops that is the continue function.

Leave a Comment