i = 0
numbers = []
while i < 6:
print("The number is %d." %i) #目前的i
numbers.append(i)
i += 1
print("Number now:",numbers ) #目前清單numbers的元素
print("At the bottom i is %d." %i) #執行i=i+1後的i
for num in numbers: #這時numbers已經變成[0,1,2,3,4,5]
print(num)
運作結果
PS E:\tonyc\Documents\Vs workspace> cd ‘e:\tonyc\Documents\Vs workspace’; ${env:PYTHONIOENCODING}=‘UTF-8’; ${env:PYTHONUNBUFFERED}=‘1’; & ‘D:\Anboot\Python\python.exe’ ‘c:\Users\tonyc.vscode\extensions\ms-python.python-2019.3.6558\pythonFiles\ptvsd_launcher.py’ ‘–default’ ‘–client’ ‘–host’ ‘localhost’ ‘–port’ ‘58393’ ‘e:\tonyc\documents\vs workspace\the hard way\ex33(while
循環).py’
The number is 0.
Number now: [0]
At the bottom i is 1.
The number is 1.
Number now: [0, 1]
At the bottom i is 2.
The number is 2.
Number now: [0, 1, 2]
At the bottom i is 3.
The number is 3.
Number now: [0, 1, 2, 3]
At the bottom i is 4.
The number is 4.
Number now: [0, 1, 2, 3, 4]
At the bottom i is 5.
The number is 5.
Number now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6.
1
2
3
4
5
思考
把while循環改寫成一個函數的形式
#将上述while循環改寫成一個函數的形式
def test_while(test_num):
i = 0
numbers = []
while i < test_num:
print("The number is %d." %i)
numbers.append(i)
i += 1
print("Number now:",numbers )
print("At the bottom i is %d." %i)
for num in numbers:
print(num)
test_while(6)
無非是添加參數和定義函數的問題,細心想想就可以解決