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.
0
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)
无非是添加参数和定义函数的问题,细心想想就可以解决