Geek University

The break statement

The break statement  is used to terminate a loop in Python. It is usually used inside an if statement that defines the condition for breaking out of the loop. The program execution is resumed at the next statement after the body of the loop.

Here is an example:

word = input('Type a word that is less than 5 characters long: ')
letterNumber = 1

for i in word:
    print ('Letter', letterNumber, 'is', i)
    letterNumber+=1
    if letterNumber > 5:
            print('The word you have entered is more than 5 characters long.')
            break

The code above will print each letter of the word you enter. If you enter a word that is more than 5 characters long, the break statement inside the if statement will end the loop after the fifth letter:

Type a word that is less than 5 characters long: Hello World!
Letter 1 is H
Letter 2 is e
Letter 3 is l
Letter 4 is l
Letter 5 is o
The word you have entered is more than 5 characters long.

Notice how only the first five letters were printed. The break statement ended the loop because the string was too long.

If you place a break statement inside a nested loop (a loop inside another loop), it will terminate the innermost loop.

Subscribe to our Newsletter

Like us on Facebook

Share on Twitter

top
Developed by Signum Soft