练习33--while循环

一 相关知识

1 while循环

  • 只要一个布尔表达式是 True,while-loop 就会一直执行它下面的代码块。
  • 它所做的只是像 if 语句一样的测试,但是它不是只运行一次代码块,而是在while 是对的地方回到顶部再重复,直到表达式为 False。
  • 但是 while-loop 有个问题:有时候它们停不下来。但大多数情况下,你肯定是需要你的循环最终能停下来的。为了避免这些问题,你得遵守一些规则:
    • 1. 保守使用 while-loop,通常用 for-loop 更好一些。
    • 2. 检查一下你的 while 语句,确保布尔测试最终会在某个点结果为 False。
    • 3. 当遇到问题的时候,把你的 while-loop 开头和结尾的测试变量打印出来,看看它们在做什么。
2 for-loop 和和while-loop 的区别是什么?
  • for-loop 只能迭代(循环)一些东西的集合,而 while loop 能够迭代(循环)任何类型的东西。不过,while-loop 很难用对,而你通常能够用 for-loop完成很多事情

二 代码

1 源代码ex33.py

 1 i = 0
 2 numbers = []
 3 
 4 while i < 6:
 5 print(f"At the top i is {i}")
 6 numbers.append(i)
 7 
 8 i = i + 1
 9 print("Numbers now: ", numbers)
10 print(f"At the bottom i is {i}")
11 
12 print("The numbers: ")
13 
14 for num in numbers:
15 print(num)

2 修改后的代码

 1 numbers = []
 2 
 3 def list(a,b):
 4     m = a
 5     n = b
 6     i = 0
 7     while i < m:
 8         print(f"At the top i is {i}")
 9         numbers.append(i)
10         
11         i = i + n
12         print("Numbers now: ",numbers)
13         print(f"At the bottom i is {i}")
14     """
15     for i in range(0,m,n):
16         print(f"At the top i is {i}")
17         numbers.append(i)
18         
19         print("Numbers now: ",numbers)
20         print(f"At the bottom i is {i}")
21     """
22 
23 a = int(input("请输入循环控制条件:"))
24 b = int(input("请输入每次循环中i的增量:"))
25 list(a,b)
26 print("The numbers:")
27 for num in numbers:
28     print(num)

3 执行结果

PS E:3_work4_python2_code_python2_LearnPythonTheHardWay> python ex33.py
请输入循环控制条件:6
请输入每次循环中i的增量:2
At the top i is 0
Numbers now:  [0]
At the bottom i is 2
At the top i is 2
Numbers now:  [0, 2]
At the bottom i is 4
At the top i is 4
Numbers now:  [0, 2, 4]
At the bottom i is 6
The numbers:
0
2
4
原文地址:https://www.cnblogs.com/luoxun/p/13322183.html