What is Break Statement in Python With Example

In Python, the break statement is used to exit or terminate a loop prematurely. It is primarily used within for and while loops to stop the execution of the loop’s block of code and move on to the next section of the program.

Here’s an example to illustrate the usage of the break statement in a while loop:

count = 0

while count < 5:
    print("Count:", count)
    if count == 3:
        break
    count += 1

print("Loop ended")Code language: Python (python)

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Loop endedCode language: Python (python)

In the above code, the while loop is executed until the count variable reaches a value of 3. When count becomes 3, the break statement is encountered, causing an immediate exit from the loop. Consequently, the program moves on to the statement after the loop, printing “Loop ended.”

The break statement can also be used in a for loop in a similar manner to prematurely terminate the loop.

How do you add a break in Python?

To add a break statement in Python, you simply need to write the keyword break at the point where you want to exit the loop. The break statement should be placed within the loop’s block of code, where you want to stop the iteration and move on to the next section of the program.

Here’s an example that demonstrates how to add a break statement in a while loop:

while True:
    user_input = input("Enter a number (or 'q' to quit): ")
    if user_input == 'q':
        break
    number = int(user_input)
    result = number * 2
    print("The result is:", result)Code language: Python (python)

In this code, the while loop continues indefinitely until a user enters the letter ‘q’ as input. When the input matches ‘q’, the if statement is executed, and the break statement is encountered, causing an immediate exit from the loop.

Note that the condition True is used for the while loop, which ensures that the loop keeps running until the break statement is encountered.

Read More;

  • Dmytro Iliushko

    I am a middle python software engineer with a bachelor's degree in Software Engineering from Kharkiv National Aerospace University. My expertise lies in Python, Django, Flask, Docker, REST API, Odoo development, relational databases, and web development. I am passionate about creating efficient and scalable software solutions that drive innovation in the industry.

    View all posts

Leave a Comment