while迴圈語句及練習題 Python 編程中 while 語句用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重覆處理的相同任務。其基本形式為: while 判斷條件: 執行語句...... 執行語句可以是單個語句或語句塊。判斷條件可以是任何表達式,任何非零、或非空(null)的值均 ...
while迴圈語句及練習題
Python 編程中 while 語句用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重覆處理的相同任務。其基本形式為: while 判斷條件: 執行語句...... 執行語句可以是單個語句或語句塊。判斷條件可以是任何表達式,任何非零、或非空(null)的值均為true。
當判斷條件假 false 時,迴圈結束。
實例:
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print("Good bye!")
運行結果:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
continue 和 break 用法
while 語句時還有另外兩個重要的命令 continue,break 來跳過迴圈,continue 用於跳過該次迴圈,break 則是用於退出迴圈,此外"判斷條件"還可以是個常值,表示迴圈必定成立,具體用法如下:
i = 1
while i < 10:
i += 1
if i%2 > 0: # 非雙數時跳過輸出
continue
print(i) # 輸出雙數2、4、6、8、10
運行結果:
2
4
6
8
10
i = 1
while 1: # 迴圈條件為1必定成立
print(i) # 輸出1~10
i += 1
if i > 10: # 當i大於10時跳出迴圈
break
運行結果:
1
2
3
4
5
6
7
8
9
10
無限迴圈
如果條件判斷語句永遠為 true,迴圈將會無限的執行下去,如下實例:
var = 1
while var == 1 : # 該條件永遠為true,迴圈將無限執行下去
num = input("Enter a number :")
print ("You entered: ", num)
print ("Good bye!")
Enter a number :3
You entered: 3
Enter a number :4
You entered: 4
Enter a number :5
You entered: 5
Enter a number :6
You entered: 6
Enter a number :7
You entered: 7
Enter a number :8
You entered: 8
Enter a number :100
You entered: 100
Enter a number :Traceback (most recent call last):
File "c:/1.py", line 76, in <module>
# num = input("Enter a number :")
KeyboardInterrupt
註意:以上的無限迴圈你可以使用 CTRL+C 來中斷迴圈。
迴圈使用 else 語句
在 python 中,while … else 在迴圈條件為 false 時執行 else 語句塊:
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")
運行結果:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
相關練習題
1.輸出1,2,3,4,5,6,8,9,10
count = 1
while count <= 10:
if count == 7:
pass
else:
print(count)
count = count + 1
2.輸出1-100所有數的和
n = 1
m = 0
while n < 101:
m = m + n
n = n + 1
print(m)
3.輸出100以內所有奇數
n = 1
while n < 101:
temp = n % 2
if temp == 0:
print(n)
else:
pass
n = n +1
4.輸出1-2+3-4+5.....99所有數的和
n = 1
m = 0
while n < 100:
temp = n % 2
if temp == 0:
m = m - n
else:
m = m + n
n = n + 1
print(m)
參考資料:
1.Python While 迴圈語句 | 菜鳥教程:https://www.runoob.com/python/python-while-loop.html