python基礎之循環與叠代器
阿新 • • 發佈:2018-11-09
tro bsp div 變量 python基礎 += col 集合 遍歷
循環
python 循環語句有for循環和while循環。
while循環
while循環語法
while 判斷條件: 語句
#while循環示例 i = 0 while i < 10: i += 1; print(i)
while else 語句 語法
while 判斷條件: 語句 else: 語句
#while else 示例 n = 0 while n < 10: n += 1; print(n); else: print("n不小於10")
for循環
for循環可以變量任何序列項目,比如list,set,tuple,字符串。
for循環語法:
for 變量 in 序列: 語句 else: 語句
#for循環示例 str = "1234567890"; for s in str: print(s);
叠代器
叠代器是一個可以記住遍歷的位置的對象。
叠代器對象從集合的第一個元素開始訪問,直到所有的元素被訪問完結束。叠代器只能往前不會後退。
叠代器有兩個基本的方法:iter()創建叠代器 和 next()訪問叠代器。
字符串,集合,列表或元組對象都可用於創建叠代器。
#使用for循環訪問示例 tuple = (1,2,3,4,5) it = iter(tuple) for x in it: pass #print(x) #使用while循環訪問示例 import sys ite = iter(tuple) while True: try: pass print (next(ite)) except StopIteration: sys.exit()
python基礎之循環與叠代器