Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

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-inlen function.

 

Remember that thebreak statement can be used with thefor 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!