笨办法学Python3 习题33 while 循环

while 循环

  • 只要循环语句中的条件布尔值为True ,就会不停的执行下面的代码块 命令。
  • while循环是无边界循环,for in 循环是有边界循环
  • 和 if 语句的相似点都是检查一个布尔表达式的真假,if 语句是执行一次,while 循环是执行完跳回到while 顶部,如此重复,直到布尔值为假False
  • 尽量少用 while 循环,大部分时候用 for in 循环是更好选择

 

 1 i = 0                          # 第一种while 循环 写法
 2 numbers = []                   # 把空数组赋值给变量numbers
 3 
 4 while i < 6:                   # 进入while 循环 当i<6:
 5     print(f'At the top is {i}')    # 打印  i的头部数
 6     numbers.append(i)              # 变量numbers 尾部追加 i 数字
 7 
 8     i+=1                           # i 每次自增1
 9     print("Numbers now:",numbers)  # 记得加逗号//打印 数组现在:
10     print(f"At the bottom is {i}") # 打印 i的底部数
11 
12 print("The numbers :")         # 打印 这个数字是: 
13 for num in numbers:            # 用for循环来循环数组numbers
14     print(num)                      # 打印 num 变量
15 
16 
17 
18 
19 shuzu = []                      # 第二种for in 循环语句改写
20 
21 for t in range(0,6):
22     print(f"top of t:{t}")
23     shuzu.append(t)
24     print(f"shuzu:",shuzu)
25     t+=1
26     print(f"bottom of t:{t}")
27 
28 print(f"The shuzu:")
29 for shu in shuzu:
30     print(shu)

 

PS C:\Users\Administrator\lpthw> python ex33.py
At the top is 0
Numbers now: [0]
At the bottom is 1
At the top is 1
Numbers now: [0, 1]
At the bottom is 2
At the top is 2
Numbers now: [0, 1, 2]
At the bottom is 3
At the top is 3
Numbers now: [0, 1, 2, 3]
At the bottom is 4
At the top is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom is 5
At the top is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom is 6
The numbers :
0
1
2
3
4
5
top of t:0
shuzu: [0]
bottom of t:1
top of t:1
shuzu: [0, 1]
bottom of t:2
top of t:2
shuzu: [0, 1, 2]
bottom of t:3
top of t:3
shuzu: [0, 1, 2, 3]
bottom of t:4
top of t:4
shuzu: [0, 1, 2, 3, 4]
bottom of t:5
top of t:5
shuzu: [0, 1, 2, 3, 4, 5]
bottom of t:6
The shuzu:
0
1
2
3
4
5

 

 

 

posted @ 2023-10-12 20:31  萹豆  阅读(9)  评论(0编辑  收藏  举报