Python break statement

The break statement in Python is used to exit or break out of a loop prematurely. It is typically used within conditional statements (such as while or for loops) to terminate the loop before its natural end. When a break statement is encountered, the program immediately exits the loop and continues with the next statement after the loop.

Here's an example that demonstrates the usage of break:

Example
while True:
    user_input = input("Enter a number (type 'exit' to quit): ")
    
    if user_input == 'exit':
        break
    
    number = int(user_input)
    square = number ** 2
    print("The square of", number, "is", square)
    
print("Loop ended.")

In this example, the program repeatedly asks the user to enter a number. If the user types "exit," the break statement is executed, and the loop is terminated. Otherwise, the program calculates and prints the square of the entered number. The loop continues until the user types "exit."

When executed, the output would look like this:

Example
Enter a number (type 'exit' to quit): 5
The square of 5 is 25
Enter a number (type 'exit' to quit): 3
The square of 3 is 9
Enter a number (type 'exit' to quit): exit
Loop ended.

As shown in the example, the loop ends as soon as the user enters "exit," and the program continues with the statement after the loop, which in this case is printing "Loop ended."