#!/usr/bin/python
# Filename:break.py
while True:
s = raw_input('Enter something
if s =='quit:
break
print 『Length of the string is
print 'Done'
(源文件:code/break.py.)
輸出
$ python break.py
Enter something:Programming
Length of the string is 18
Enter something: When the work
Length of the string is 21
Enter something:if you wanna
Length of the string is 37
Enter something: use Python!
Length of the string is 12
Enter something:quit
Done
它如何工作
在這個程序中,我們反覆地取得用戶地輸
入,然後列印每次輸入地長度。我們提供了
一個特別的條件來停止程序,即檢驗用戶的
輸入是否是『quit。通過終止 循環到達程序
結尾來停止程序。
輸入字符串的長度通過內建的 len函數取
得。
記住,break語句也可以在for 循環中使
用。
G2的Python詩
我在這裡輸入的是我所寫的一段小詩,稱為
G2的Python詩:
Programming is fun
When the work is done
if you wanna make your work als
use Python!
Python 的 for 循環從根本上不同
於 C/C++的 for 循環。C#程序
員會注意到Python 的for 循環
與C#中的 foreach 循環十分類
似。Java程式設計師會注意到它與
Java 1.5 中的 for (inti:
IntArray)相似。在 C/C++中,
如果你想要寫 for (inti=O;i< 5;
i++),那麼用Python,你寫成
for i in range(0,5)。你會注意
到,Python的 for 循環更加簡
單、明白、不易出錯。