A Byte of Python

The break statement

The break statement is used to break out of a loop statement i.e. stop the execution of a looping statement, even if the loop condition has not become False or the sequence of items has been completely iterated over.

An important note is that if you break out of a for or while loop, any corresponding loop else block is not executed.

Using the break statement

Example 6.4. Using the break statement

				
#!/usr/bin/python
# Filename: break.py

while True:
	s = raw_input('Enter something : ')
	if s == 'quit':
		break
	print 'Length of the string is', len(s)
print 'Done'
				
				

Output

				
$ python break.py
Enter something : Programming is fun
Length of the string is 18
Enter something : When the work is done
Length of the string is 21
Enter something : if you wanna make your work also fun:
Length of the string is 37
Enter something :       use Python!
Length of the string is 12
Enter something : quit
Done
				
				

How It Works

In this program, we repeatedly take the user's input and print the length of each input each time. We are providing a special condition to stop the program by checking if the user input is 'quit'. We stop the program by breaking out of the loop and reach the end of the program.

The length of the input string can be found out using the built-in len function.

Remember that the break statement can be used with the for loop as well.

G2's Poetic Python

The input I have used here is a mini poem I have written called G2's Poetic Python:

Programming is fun
When the work is done
if you wanna make your work also fun:
	use Python!