循環結構(while 、for)
什么是循環結構
循環機構就是重復執行某段代碼塊
為什么要用循環結構
人類某些時候需要重復做某件事情
所以程序中必須有相應的機制來控制計算機具備人的這種循環做事的能力
如何使用循環結構
python中有while和for兩種循環機制
while循環語法
while循環稱之為條件循環,語法如下:
while 條件:
代碼1
代碼2
代碼3
else:
代碼a
while的運行步驟:
步驟1:如果條件為真,那么執行:代碼1、代碼2、代碼3、……
步驟2:執行完畢代碼塊后再次判斷條件,如果條件繼續為True則再次執行:代碼1、代碼2、代碼3、……, 如果條件為False了,則結束while循環。
步驟3:如果while循環不是通過break提前終止的,則會在循環完整結束后執行else內的代碼a
結束循環的條件:
1.判斷條件為False
2.break提前跳出循環
continue 提前結束當前一次循環,進入下一次循環
while循環案例
案例一:
username = "jason"
password = "123"
count = 0 # 記錄錯誤次數
while count < 3: # 最多錯誤3次
inp_name = input("請輸入用戶名:")
inp_pwd = input("清輸入密碼:")
if inp_name == username and inp_pwd == password:
print("登陸成功")
else:
print("輸入的用戶名或用戶錯誤")
count += 1
案例二:while+break的使用
上述案例使用while循環后,代碼精簡很多,但問題是用戶輸入了正確的用戶名和密碼后無法結束循環,那如何結束掉循環呢?這就需要使用到break了!
username = "jason"
password = "123"
count = 0 # 記錄錯誤次數
while count < 3: # 最多錯誤3次
inp_name = input("請輸入用戶名:")
inp_pwd = input("清輸入密碼:")
if inp_name == username and inp_pwd == password:
print("登陸成功")
break # 用於結束循環
else:
print("輸入的用戶名或用戶錯誤")
count += 1
案例三:while循環嵌套+break
如果while循環嵌套了很多層,要想退出每一層循環則需要在每一層循環都有一個break
username = "jason"
password = "123"
count = 0 # 記錄錯誤次數
while count < 3: # 最多錯誤3次
inp_name = input("請輸入用戶名:")
inp_pwd = input("清輸入密碼:")
if inp_name == username and inp_pwd == password:
print("登陸成功")
while True:
cmd = input(">>: ")
if cmd == 'quit':
break # 用於結束本層循環,即第二層循環
else:
print('run <%s>' % cmd)
break # 用於結束本層循環,即第一層循環
else:
print("輸入的用戶名或用戶錯誤")
count += 1
案例四:while+continue的使用
break代表結束本層循環,而continue則用於結束本次循環,直接進入下一次循環
# 打印1到10之間,除7以外的所有數字
number=1
while number<11:
if number == 7:
continue # 結束掉本次循環,即本次循環continue之后的代碼就不會執行了,而是直接進入下一次循環。
print(number)
num += 1
案例五:while+else的使用
在while循環的額后面,可以使用else語句,當while循環正常執行完並且中間沒有被break中止的話,就會執行else后面的語句,所以可以用else來驗證,循環收否正常結束
count = 0
whlie coount <= 5:
count += 1
print("Loop", count)
else:
print("循環正常執行完啦")
print("-----out of while loop -----")
輸出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循環正常執行完啦 #沒有被break打斷,所以執行了該行代碼
-----out of while loop -----
如果執行過程中被break中止,就不會執行else的語句
count = 0
while count <= 5:
count += 1
if count == 3:
break
print("Loop", count)
else:
print("循環正常執行完啦")
print("-----out of while loop -----")
輸出
Loop 1
Loop 2
-----out of while loop ----- #由於循環被break打斷了,所以不執行else后的輸出語句
練習1:
尋找 1到100之間數字7最大的倍數
num = 100
while num > 0:
if num % 7 == 0:
print(num)
break
num -= 1
練習2:
猜年齡 且最多猜3次
age = 18
count = 0
while count < 3:
count += 1
guess = int(input('>>: '))
if guess > age:
print("太大了")
elif guess < age:
print("猜小了")
else:
print("猜對啦")
break
else:
print("三次都沒猜對,下次再來玩吧")
for循環語法
for 變量名 in 可迭代對象:
代碼一
代碼二
。。。
# 例1
for item in ['a', 'b', 'c']:
print(item)
# 運行結果
a
b
c
# 參照例1來介紹for循環的運行步驟
# 步驟1: 從列表['a', 'b', 'c']中讀出第一個值賦值給item(item = 'a'), 然后執行循環體代碼
# 步驟2: 從列表['a', 'b', 'c']中讀出第二個值賦值給item(item = 'b'), 然后執行循環體代碼
# 步驟3: 重復上述過程直至列表中的值讀盡
案例一:打印數字0-5
# 簡單版:for循環的實現方式
for count in range(6):
print(count)
# 復雜版:while循環的實現方式
count = 0
while count < 6:
print(count)
count += 1
案例二:遍歷字典
# 簡單版:for循環的實現方式
for k in {'name':'jason','age':18,'gender':'male'}: # for 循環默認取的是字典key
print(k)
# 復雜版:while循環確實可以遍歷字典,后續將會迭代器部分詳細介紹
案例三:for循環嵌套
# 請用for循環嵌套的方式打印如下圖形:
*****
*****
*****
for i in range(3):
for j in range(5):
print('*', end='')
print() # print()可以換行
注意:break與continue也可以用於for循環,用法與在while循環中相同
練習一:
打印九九乘法表
for i in range(1,10):
for j in range(i,10):
res = i*j
print("{x}x{y}={r}".format(x=i,y=j,r=res), end=' ')
print()
# 結果:
1x1=1 1x2=2 1x3=3 1x4=4 1x5=5 1x6=6 1x7=7 1x8=8 1x9=9
2x2=4 2x3=6 2x4=8 2x5=10 2x6=12 2x7=14 2x8=16 2x9=18
3x3=9 3x4=12 3x5=15 3x6=18 3x7=21 3x8=24 3x9=27
4x4=16 4x5=20 4x6=24 4x7=28 4x8=32 4x9=36
5x5=25 5x6=30 5x7=35 5x8=40 5x9=45
6x6=36 6x7=42 6x8=48 6x9=54
7x7=49 7x8=56 7x9=63
8x8=64 8x9=72
9x9=81
練習二:
打印金字塔
max_piles = 7
for i in range(1, max_piles+1):
temp_str = '*'*(i*2-1)
print(temp_str.center(2*max_piles-1))
# 結果:
*
***
*****
*******
*********
***********
*************