笨办法学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一行的值,互相独立了。为什么呢?

你可能感兴趣的:(笨办法学Python习题33:while循环)