ex33 while循环

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)

无非是添加参数和定义函数的问题,细心想想就可以解决

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值