#!/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'
(源文件:code/break.py)
輸出
$ 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
它如何工作
在這個程序中,我們反復地取得用戶地輸入,然后打印每次輸入地長度。我們提供了一個特別的條件來停止程序,即檢驗用戶的輸入是否是'quit'。通過 終止 循環(huán)到達程序結尾來停止程序。
輸入字符串的長度通過內(nèi)建的 len 函數(shù)取得。
記住,break 語句也可以在 for 循環(huán)中使用。
我在這里輸入的是我所寫的一段小詩,稱為 G2 的 Python 詩:
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!