python while循环

当count=0,以count+1形式无限循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env   python
# -*- coding:utf-8 -*-
count = 0
while True:
    print("count:", count)
    count = count+1
     
执行结果:
.....
count: 1781738
count: 1781739
count: 1781740
count: 1781741
count: 1781742
count: 1781743
count: 1781744
count: 1781745
count: 1781746
......


猜测游戏:当用户猜测次数超过3次即将退出,猜测正确也退出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env   python
# -*- coding:utf-8 -*-
age_of_xcn = 20
count = 0
while True:
    if count ==3:
        break
    guess_age = int(input("guess age:"))
    if guess_age == age_of_xcn:
        print("yes,you got it")
        break
    elif guess_age > age_of_xcn:
        print("think smaller")
    else:
        print("think bigger")
    count +=1
     
  
 执行结果:
 guess age:5
think bigger
guess age:3
think bigger
guess age:2
think bigger
 
进程已结束,退出代码0

python while循环


优化后:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env   python
# -*- coding:utf-8 -*-
age_of_xcn = 20
count = 0
while count < 3:
    guess_age = int(input("guess age:"))
    if guess_age == age_of_xcn:
        print("yes,you got it")
        break
    elif guess_age > age_of_xcn:
        print("think smaller")
    else:
        print("think bigger")
    count += 1
else:
    print("bay bay")

python while循环




本文转自 baishuchao 51CTO博客,原文链接:http://blog.51cto.com/baishuchao/1933086