笨办法学Python习题33:while循环

  1. 将这个while循环改成一个函数,将测试条件(i < 6)中的 6 换成一个变量。
def whifunc(a):
	i = 0
	numbers = []

	while i < a:
		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
		
whifunc(int(raw_input('a= ')))
  1. 为函数添加另外一个参数,这个参数用来定义第 8 行的加值 +1 ,这样你就可以让它加任意值了。
def whifunc(a, s):
	i = 0
	numbers = []

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

	print "The numbers: "

	for num in numbers:
		print num
		
whifunc(int(raw_input('a= ')), int(raw_input('s= ')))
  1. 使用for-looprange把这个脚本再写一遍。你还需要中间的加值操作吗?如果不去掉它,会有什么样的结果?
    def whifunc(a, s):
    	i = 0
    	numbers = []
    
    	for i in range (0, a):
    		print "At the top i is %d" % i
    		numbers.append(i)
    	
    		i = i + s
    		print "Numbers now: ",numbers
    		print "At the bottom i is %d" % i
    
    	print "The numbers: "
    
    	for num in numbers:
    		print num
    		
    whifunc(int(raw_input('a= ')), int(raw_input('s= ')))
    发现这样做的时候,step不会更新,结果还是和+1一样,于是查找资料,发现for循环可以添加三个参数,开始值,结束值,step,这样就可以+step了,而且i = i + s这一行不需要了。
    def whifunc(a, s):
    	i = 0
    	numbers = []
    
    	for i in range (0, a, s):
    		print "At the top i is %d" % i
    		numbers.append(i)
    	
    		# i = i + s
    		print "Numbers now: ",numbers
    		print "At the bottom i is %d" % i
    
    	print "The numbers: %s" % numbers
    """把下面这两行去掉,改成上面这行后面这样直接输出列表。"""
    	# for num in numbers:
    		# print num
    我又测试了不在函数里的情况,直接拿原代码改,当第三个参数为1,和i = i + s中s值一样时,和不加第三个参数效果一样
    i = 0
    numbers = []
    
    for i in range (0, 6, 1):
        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
    但是当第三个参数和s值不一样时,第三个参数控制print "At the top i is %d" % i一行的值,而s值控制了print "At the bottom i is %d" % i一行的值,互相独立了。为什么呢?
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值