笨方法学python 习题33

习题33
python:3.9

i = 0
numbers = []


while i < 6:
    print ("At the top i is %d" % i)
    numbers.append(i)
    i = i + 1
    print ("Numbers now: ",numbers)
    print ("At the bottom i is %d" % i)


print ("The numbers: ")

for num in numbers:
    print (num)

运行结果

 0
Numbers now:  [0]
At the bottom i is 1
At the top i is 1
Numbers now:  [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now:  [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now:  [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now:  [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now:  [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers: 
0
1
2
3
4
5

加分习题
1.将这个 while 循环改成一个函数,将测试条件(i < 6)中的 6换成一个变量。

def test(v):
    i=0
    numbers = []
    while i <v :
        print ("At the top i is %d "%i)
        numbers.append(i)
        i = i +1
       
        print ("Numbers now:",numbers)
        print ("At the bottom i is %d " %i)
        print ("The numbers:")

    for num in numbers:
        print (num)
    

test (6)

2.使用这个函数重写你的脚本,并用不同的数字进行测试。
3.为函数添加另外一个参数,这个参数用来定义第 8 行的加值+ 1,这样你就可以让它任意加值了。

def test(v):
    i=0
    numbers = []
    while i <v :
        print ("At the top i is %d "%i)
        numbers.append(i)
        k = i +3
       
        print ("Numbers now:",numbers)
        print ("At the bottom i is %d " %k)
        print ("The numbers:")

    for num in numbers:
        print (num)
    

test (6)

这个是换里变量k,之后运行就停不下来了,这个时候你按ctrl+c就OK了
4.再使用该函数重写一遍这个脚本。看看效果如何。

5.接下来使用 for-loop和 range把这个脚本再写一遍。你还需要中间的加值操作吗?如果你不去掉它,会有什么样的结果?

这个是中间没有加值的

numbers = []
for i  in range (0,10):
    print ("At the top i is %d "%i)
    numbers.append(i)
    
       
    print ("Numbers now:",numbers)
    print ("At the bottom i is %d " %i)
    print ("The numbers:")

for num in numbers:
        print (num)

这是加了的

numbers = []
for i  in range (0,10):
    print ("At the top i is %d "%i)
    numbers.append(i)
    i = i +1
       
    print ("Numbers now:",numbers)
    print ("At the bottom i is %d " %i)
    print ("The numbers:")

for num in numbers:
        print (num)

输出结果相同
很有可能你会碰到程序跑着停不下来了,这时你只要按着 CTRL再敲c (CTRL-c),这样程序就会中断下来了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值