迭代器 iterator
1,物件是可iterator的
2,for可以遍歷 iterator_obj
-list
-string
-tuple
-dict
-file
3,迴圈體與檔案
1)while 和readline
readline:讀成功返回正常的字串;讀到檔案的末尾返回空字串
print fr.readline().rstrip('\n') 列印的無多餘的空行
2)for和file_obj
eg1:
rfile=open('a.txt','r')
str=rfile.readline()
str=str.rstrip('\n')
while str !='';
print str
str=rfile.readline()
str=str.rstrip('\n')
print "read finish!"
rfile.close()
eg2:
rfile=open('a.txt','r')
for str in rfile:
str=str.rstrip('\n')
print str
print "read finish!"
rfile.close()
注意寫while迴圈的時候:迴圈體外有迴圈變數的初始化 + 迴圈體內有迴圈變數的修正
第十五講 迴圈體for基礎
語法結構 for target in sequences code.code.else code.code.注 1,sequences是序列,包含列表 list 元組 tuple 字串 string 檔案 file 但是比如整形數字 80 這樣的是不可以的 2,條件結尾有冒號 3,迴圈體無花括號,由...
迴圈體與else語句
大家一定非常熟悉else關鍵字語句,else通常是用來配合if語句使用的,但是在python的else語句並不只能用在if語句之後,還可以用在迴圈語句甚至try異常處理語句中,這雖然不是什麼秘密,但是很多人沒有發現它的好處。for else 預設情況下,只有當for迴圈語句正常執行後,最後才會執行e...
迴圈體與else搭配陷阱
迴圈過程正常執行,沒有被break則執行else下面的語句 list range 100 for x in list if x 20 19 print x break else print else 19這裡找到乙個數字,break跳出了迴圈,else不會執行.通常迴圈體 else搭配用來處理遍歷失...