一.while循環
1.1基本格式:
while 條件:
如果條件成立之后循環執行的子代碼塊
1.2while+break循環語句
while 條件:
如果條件成立執行子代碼塊
break(用於結束本層循環)
1.3while+continue循環語句
continue會讓循環體代碼直接回到條件判斷處重新判斷,從而達到跳過某些內容的效果。例如:
# 使用while循環找出100以內的最大的6的倍數。 count = 100 while count > 0: if count % 6 == 0: print(count) break count -= 1
流程圖如下:
# 使用while循環打印1到10,其中不含4 count = 0 while count < 11: if count == 4: count += 1 continue print(count) count += 1
流程圖如下:
1.4while+else循環語句
當while循環沒有被人為中斷(break)的情況下才會走else代碼塊。
簡單的一個例子:
count = 0 while count < 5: print(count) count += 1 else: print('沒了')
二.死循環語句
一直循環下去的程序,他會讓計算機CPU負載加大,甚至崩潰。
while True: print(1)
三.for循環
for循環相比較while循環語法更加簡潔,並且在循環取值更加方便,在編程中用的較為頻繁。
name_list = ['zhangsan', 'lisi', 'wangerma', 'wangwu'] for i in name_list: print(i)
for 變量名 in 可迭代對象(字符串,列表,字典,元組,集合)
for循環代碼
# for循環字符串 # for i in 'hello world' # print(i)
# for循環字典:默認只能拿到k d = {'username': 'jason', 'pwd': 123, 'hobby': 'read'} for k in d: print(k, d[k])
3.1range關鍵字
# 關鍵字range # 第一種:一個參數 從0開始 顧頭不顧尾 for i in range(10): print(i) # 第二種:兩個參數 自定義起始位置 顧頭不顧尾 for i in range(4, 10): print(i) # 第三種:三個參數 第三個數字用來控制等差值 for i in range(2, 100, 10): print(i)
# range在不同版本的解釋器中 本質不同 # 在python2.X中range會直接生成一個列表 # 在python2.X中有一個xrange也是迭代器 # 在python3.X中range是一個迭代器 節省內存空間 # '''python2.X中xrange就是python3.x里面的range'''
3.2for+break語句
for i in range(10): if i == 4: break print(i)
3.3for+continue
continue功能也相當於結束本次循環。
for i in range(10): if i == 4: continue print(i)
3.4for+else循環的嵌套使用
for i in range(3): for j in range(5): print("*", end='') print(i,j)