跟大多數編程語言一樣,python中的迴圈有兩種: while迴圈和for迴圈 首先,介紹一下while迴圈,結合案例做一些練習。 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++while迴圈語法結構:while ...
跟大多數編程語言一樣,python中的迴圈有兩種:
while迴圈和for迴圈
首先,介紹一下while迴圈,結合案例做一些練習。
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
while迴圈語法結構:
while 條件表達式:
代碼
語法特點:
1.有初始值
2.條件表達式
3.變數【迴圈體內計數變數】的自增自減,否則會造成死迴圈
使用條件:迴圈的次數不確定,依靠迴圈條件來結束
目的:為了將相似或者相同的代碼變得更加簡潔,使得代碼可以重覆利用
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
案例一,輸出1~100之間的數
# while 的使用,案例一,輸出1~100之間的數 # 定義索引變數 # index = 1 # while index <= 100: # print (index) # index += 1 # pass
# 案例二:對猜拳游戲進行改進,使得可以進行多次猜拳 # 導入隨機數random模塊 # import random # while True: # print ('----------------------石頭剪刀布------------------------') # # people = input ('(0代表石頭,1代表剪刀,2代表布)請輸入:') # 用people代表人為的輸入 # computer = random.randint (0, 2) # 隨機生成一個0,2之間的整數 # if people == '0' or people == '1' or people == '2': #用於規範用戶的輸入,限制只能輸入0,1,2 # people = int (people) # 字元串轉為int類型 # print ('你的輸入為:{}'.format (people)) # print ('電腦的為:{}'.format (computer)) # if people == computer: # print ('好吧,打平了~~') # pass # elif people == 0 and computer == 1: # print ('真棒,你贏了~') # pass # elif people == 1 and computer == 2: # print ('真棒,你贏了~') # pass # elif people == 2 and computer == 0: # print ('真棒,你贏了~') # pass # else: # print ('輸了哦~') # pass # else: # print('輸入不正確,請輸入0或1或2')
# 案例三:列印九九乘法表 # i = 1 #表示行數 1~9 # while i <= 9: #外迴圈控制行 # j = 1 #表示列數 1~9 # while j <= 9-i+1: #內迴圈控制列 # print('{}*{}={}'.format(j,10-i,j*(10-i)),end=' ') #想方設法把i,j的值與對應程式中的數對應起來 # j += 1 # print('\n') # i += 1
介紹一下for迴圈:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
for迴圈
語法特點:遍歷操作,依次取集合容器中的每個值
迴圈格式:
for 臨時變數 in 字元串,列表等:
執行代碼塊
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# 案例一,求1~100的累加和 # sum = 0 # for data in range(1,101): # sum += data # print(data,end=' ') # pass # print('\n') # print('sum=%d'%sum)
# 案例二,輸出20~101之間的偶數 # for data in range(20,102): # if data % 2 == 0: # print('%d是偶數'%data, end=' ') # pass # else: # print('%d是奇數'%data)
while迴圈和for迴圈對比:
通過對比發現:
while使用:適用於對未知的迴圈次數 用於判斷
for使用:適用於已知的迴圈次數【可迭代對象遍歷】
迴圈語句結合else語句的案例:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
迴圈和else語句的搭配使用:
for 變數 in 遍歷對象:
執行代碼塊
else:
迴圈體退出時執行的代碼
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
''' 案例,限定用戶登陸的次數,一旦三次沒有登錄成功就提示用戶已被鎖定 思路: 用for迴圈控制嘗試登陸的次數,執行完整個for迴圈沒有登錄成功則鎖定賬戶 所採用的結構: for 變數 in 遍歷對象: 執行代碼塊 else: 迴圈執行結束後,要執行的內容 ''' usr = 'haha' pwd = '123' for i in range(3): username = input('請輸入用戶名:') password = input('請輸入密碼:') if usr == username and pwd == password: print('歡迎%s'%usr) break # 用戶名和密碼都正確跳出迴圈,登陸成功 pass pass else: # 如果三次沒有登錄成功,鎖定賬戶。只要迴圈語句中break語句沒有執行,else就會執行
print('該賬戶已被鎖定')
迴圈語句和else搭配使用總結:
只要迴圈語句中break語句沒有執行,else就會執行