Note:
高能:语句结构都是由关键字开头,用冒号结束!
一:语句结构
while 判断条件:
语句
二:基本规则
(1)使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
(2)可以通过设置条件表达式永远不为 false 来实现无限循环
(3)在 while … else 在条件语句为 false 时执行 else 的语句块
三:条件为真
不为 0, True, 'None', 字符串不为空串
四:嵌套结构
五:break和continue
Code:
1 # -----------------------------------------------------------------------------------------------------#
2 # while循环结构
3 # -----------------------------------------------------------------------------------------------------#
4 count = 0
5 while count < 9:
6 print('The count is:', count)
7 count = count + 1
8
9 print("Good bye!")
10
11
12 n = 100
13 my_sum = 0
14 counter = 1
15 while counter <= n:
16 my_sum = my_sum + counter
17 counter += 1
18 # if counter == 5:
19 # break
20 print("1 到 %d 之和为: %d" % (n, my_sum))
21
22
23 # -----------------------------------------------------------------------------------------------------#
24 # while无限循坏
25 # -----------------------------------------------------------------------------------------------------#
26 """
27 var = 1
28 while var == 1: # 表达式永远为 true
29 num = int(input("输入一个数字 :"))
30 print("你输入的数字是: %d", num)
31
32 """
33
34
35 # -----------------------------------------------------------------------------------------------------#
36 # while … else 条件语句
37 # -----------------------------------------------------------------------------------------------------#
38 """
39 count = 0
40 while count < 5:
41 print(count, " 小于 5")
42 count = count + 1
43 else:
44 print(count, " 大于或等于 5")
45
46 """
47
48 # -----------------------------------------------------------------------------------------------------#
49 # while循坏的应用----奇数偶数分类
50 # -----------------------------------------------------------------------------------------------------#
51
52 """
53 numbers = [12, 37, 5, 42, 8, 3]
54 even = [] # 偶数
55 odd = []
56 while len(numbers) > 0:
57 number = numbers.pop() # 表示移除的对象,
58 if number % 2 == 0: # 如果是偶数的情况
59 even.append(number)
60 else:
61 odd.append(number)
62 print('偶数:', even)
63 print('奇数:', odd)
64
65 """
66
67 # -----------------------------------------------------------------------------------------------------#
68 # while循坏的应用----猜数游戏
69 # -----------------------------------------------------------------------------------------------------#
70
71 """
72 s = int(random.uniform(1, 10)) # 得到1-10之间的随机数
73 # print(s)
74 m = int(input('输入整数:'))
75 while m != s:
76 if m > s:
77 print('大了')
78 m = int(input('输入整数:'))
79 if m < s:
80 print('小了')
81 m = int(input('输入整数:'))
82 if m == s:
83 print('OK')
84 break
85
86 """