1. 程式人生 > >Lesson 3-2 語句:循環語句

Lesson 3-2 語句:循環語句

world! pytho 區別 print project play 遍歷 關鍵字 返回

3.2 循環語句

3.2.1 while 循環語句

--- while 語句包含:關鍵字while、條件、冒號、while子句(代碼塊)。

--- 執行while 循環,首先判斷條件是否為真,如果為假,結束while循環,繼續程序中後面的語句,如果為真,執行while子句的代碼塊,執行完後調回到while循環開始的地方,重新判斷條件是否為真,如果為真,執行while子句的代碼塊,一遍一遍的循環執行,直至條件為假。

 1 a = 1
 2 while a < 10 :
 3     print(a)
 4     a = a +1
 5 
 6 print(Hello world!
) 7 8 結果: 9 /usr/bin/python3.7 /home/jlu/Projects/Python/untitled/2019-4-21/循環語句.py 10 1 11 2 12 3 13 4 14 5 15 6 16 7 17 8 18 9 19 Hello world! 20 21 Process finished with exit code 0

&、註意while 語句和if 語句的區別,當條件為真時,while語句執行完一遍後會返回開始點,if 語句執行完一遍後不返回,繼續往下執行。

3.2.2 for 循環語句

--- for 語句包含:for 關鍵字、一個變量名、in關鍵字、可叠代對象、冒號、for子句(代碼塊)。

--- for 語句含義:執行叠代(遍歷)可叠代對象次數的for子句代碼塊。

技術分享圖片
 1 lis = [1, 2, 3, 4, 5]
 2 for i in lis:
 3     print(i)
 4 
 5 total = 0
 6 for num in range(101):
 7     total = total + num
 8 print(total)
 9 
10 結果:
11 /usr/bin/python3.7 /home/jlu/Projects/Python/untitled/2019-4-21/循環語句.py
12 1
13 2
14 3
15 4
16 5
17
5050 18 19 Process finished with exit code 0
View Code

3.2.3 break 語句

--- break 語句只包含break 關鍵字,通常放在if 語句的代碼塊中使用,用於滿足一定條件時,立即結束當前叠代,並提前結束循環。

技術分享圖片
 1 total = 0
 2 for num in range(101):
 3     total = total + num
 4     if total > 2000 :
 5         break
 6 
 7 print(num,total)
 8 
 9 
10 結果:
11 /usr/bin/python3.7 /home/jlu/Projects/Python/untitled/2019-4-21/循環語句.py
12 63 2016
13 
14 Process finished with exit code 0
View Code 技術分享圖片
 1 total = 0
 2 num = 1
 3 while num < 101 :
 4     total = total + num
 5     num = num +1
 6     if total > 2000 :
 7         break
 8 
 9 print(num,total)
10 
11 
12 結果:
13 /usr/bin/python3.7 /home/jlu/Projects/Python/untitled/2019-4-21/循環語句.py
14 64 2016
15 
16 Process finished with exit code 0
View Code

3.2.4 continue 語句

--- continue 語句只包含continue 關鍵字,它結束當前叠代,並跳回到叠代開頭處,繼續進行循環條件判斷,條件為真時繼續進入循環。

 1 num = 1
 2 while num :
 3     num = num * num + 1
 4     print(str(num) + -while)
 5     if num < 100 :
 6         continue
 7     print(str(num) + -continue)
 8     if num > 1000 :
 9         break
10     print(str(num) + -break)
11 print(str(num) + -end)
12 
13 
14 結果:
15 /usr/bin/python3.7 /home/jlu/Projects/Python/untitled/2019-4-21/循環語句.py
16 2-while
17 5-while
18 26-while
19 677-while
20 677-continue
21 677-break
22 458330-while
23 458330-continue
24 458330-end
25 
26 Process finished with exit code 0

Lesson 3-2 語句:循環語句