python学习-7 条件语句 whil

2023-01-31 00:01:39 python 学习

1.死循环

while 1 == 1:
     print('ok')

结果是一直循环

 

 

2.循环

count  = 0
while count < 10:
     print(count)
     count = count +1
print(error)

 

3.练习题 

~ 使用while循环输出1 2 3 4 5 6   8 9 10

count = 1

while count <= 10 :                    # 或者count < 11
    if count == 7:
        print( )                       # 也可以添加pass,什么也不执行
    else:
       print(count)
    count = count + 1

执行结果:

1
2
3
4
5
6

8
9
10

Process finished with exit code 0

~ 求1-100的所有数的和

a = 1
b = 0
while a < 101:
    b = b + a
    a = a + 1
print(b)

输出结果:

5050

Process finished with exit code 0

 

~求1-100内所有的奇数

n = 1
while n < 101:
    js = n % 2
    if js == 0:
        print( )
    else:
        print(n)
    n = n + 1

输出结果:

1

3

5

7

9

11

13

15

17

19

21

23

25

27

29

31

33

35

37

39

41

43

45

47

49

51

53

55

57

59

61

63

65

67

69

71

73

75

77

79

81

83

85

87

89

91

93

95

97

99

~ 求1-100内所有的偶数

a = 1
while a < 101:
    b = a % 2
    if b == 0:
        print(a)
    else:
        pass
    a = a + 1

输出结果:

2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100

Process finished with exit code 0

 

相关文章