Table of Contents

Use of break statement in For loop | Pictoblox

Example Description
Learn how to use the break statement in a for loop in Python, with a simple program demonstrating its usage.

Introduction:

In this program, we are demonstrating the use of the break statement in a loop in Python. The break statement allows us to exit the loop prematurely if a certain condition is met.

Code:

#Program to demonstrate the use of break statement in loop
num = 0
for num in range(10):
 num = num + 1
 if num == 8:
  break
 print('Num has value ' + str(num))
print('Encountered break!! Out of loop')

Logic:

1. Initialize the variable “num” with a value of 0.
2. Start a for loop with the range of 10, indicating that it will run for 10 iterations.
3. Inside the loop, increment the value of “num” by 1.
4. Check if the value of “num” is equal to 8.
5. If the condition is met, use the break statement to exit the loop.
6. Print the current value of “num” inside the loop.
7. After the loop, print a message indicating that the break statement has been encountered and the program is out of the loop.

Output:

>> Num has value 1

>> Num has value 2

>> Num has value 3

>> Num has value 4

>> Num has value 5

>> Num has value 6

>> Num has value 7

>> Encountered break!! Out of loop