Break Statement in Python

As explained in the program above, we use the break statement to stop the execution of the loop and bring the control out of the loop.

Let us use the break statement in another loop now:

Example: Create a list of the odd numbers between 1 and 20 (use while, break)

number = 1
odd_numbers = []

while number:
    if number % 2 != 0:
        odd_numbers.append(number)
    if number >=20:
        break
    number += 1
print ("Odd numbers: ", odd_numbers)

In this code, if the new number is greater than 20, the code will stop the loop. Try it in your IDE and see the results.

Let us use another example. This time, we will try to stop the running of the loop whenever the number gets to 5. We will use a break statement for the for loop.

for numbers in range(1, 11):
if numbers == 5:
        break
    else:
        print(numbers)

this statement tells Python to print all numbers between 1 and 11. But the break statement asks it to stop once it gets to 5.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials