笨办法学Python习题33加分题
2017-12-28 14:37
267 查看
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
相关文章推荐
- 笨办法学python加分习题32
- 笨办法学python加分习题39
- 笨办法学Python-习题12
- 笨办法学python 习题0中 shell无法调用python
- 笨办法学python加分习题15
- 笨办法学python加分习题17
- 笨办法学Python习题33:while循环
- 笨办法学python加分习题28
- 笨办法学python加分习题29
- 笨办法学python笔记:习题14 提示和传递(结合input)
- 笨办法学python习题7 更多打印
- 笨办法学python笔记(习题32)——range()、append()用法,以及for循环用法
- while循环,习题33,笨办法学python
- 笨办法学python习题4变量和变名
- 笨办法学Python-习题2
- “笨办法”学Python习题41代码问题
- 笨办法学python习题 6字符串和文本
- 笨办法学Python习题14 提示和传递
- 笨办法学Python(习题38)——len()、join()、x.[x,x]
- 笨办法学Python-习题18-25