笨办法学Python习题33加分题

本文通过将while循环转化为函数,介绍了如何调整测试条件和加值操作,并探讨了使用for-loop和range替代while循环的效果,强调了range在遍历过程中的自动递增特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

加分习题
1. 将这个 while 循环改成一个函数,将测试条件(i < 6)中的 6 换成一个变量。
2. 使用这个函数重写你的脚本,并用不同的数字进行测试。

def list( i ):
        numbers = []
        j = 0
        while j < i:
                print("At the top number is %d" % j)
                numbers.append(j)


                j = j + 1
                print "Numbers now: ",  numbers
                print("At the bottom number is %d" % j)

                print("The numbers: ")

                for num in numbers:
                        print(num)

print("Please type in a number:")
i = int(raw_input("> ")) //attention: raw_input()默认输入的是str,需要强制转换
list( i )

3. 为函数添加另外一个参数,这个参数用来定义第 8 行的加值 + 1 ,这样你就可以让它任意加值了。
4. 再使用该函数重写一遍这个脚本。看看效果如何。

def list( i, cut ):
        numbers = []
        j = 0
        while j < i:
                print("At the top number is %d" % j)
                numbers.append(j)


                j = j + cut
                print "Numbers now: ",  numbers
                print("At the bottom number is %d" % j)

                print("The numbers: ")

                for num in numbers:
                        print(num)

print("Please type in a number:")
i = int(raw_input("> "))
print("Please type in cut off:")
cut = int(raw_input("> "))
list( i,cut)

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

def list( i ):
        numbers = []
        j = 0
        for  j in range(0,i):
                print("At the top number is %d" % j)
                numbers.append(j)

                print "Numbers now: ",  numbers
                print("At the bottom number is %d" % j)

                print("The numbers: ")

                for num in numbers:
                        print(num)

print("Please type in a number:")
i = int(raw_input("> "))
list( i )

range会自动遍历范围内的值,不需要j = j + 1

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值