当count=0,以count+1形式无限循环
#!/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次即将退出,猜测正确也退出
#!/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
优化后:
#!/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")
转载于:https://blog.51cto.com/baishuchao/1933086