WangHe685

导航

 

一、while and for

需求:猜年龄,输错三次退出,猜对退出

解决1:


age_of_oldboy = 56
count = 0
while True:
if count == 3:
print("输错三次,不能再猜了")
break
guess_age = int(input("guess age:"))
if guess_age == age_of_oldboy:
print("Great,you got it")
break
elif guess_age > age_of_oldboy:
print("猜大了")
else:
print("猜小了")
count += 1
执行结果:

guess age:11
猜小了
guess age:57
猜大了
guess age:234
猜大了
输错三次,不能再猜了

解决2:while优化版

 1 age_of_oldboy = 56
 2 count = 0
 3 while count<3:
 4     guess_age = int(input("guess age:"))
 5     if guess_age == age_of_oldboy:
 6         print("Great,you got it")
 7         break
 8     elif guess_age > age_of_oldboy:
 9         print("猜大了")
10     else:
11         print("猜小了")
12     count += 1

for循环:

解决3:for循环实现

 1 age_of_oldboy = 56
 2 count = 0
 3 for count in range(3):
 4     guess_age = int(input("guess age:"))
 5     if guess_age == age_of_oldboy:
 6         print("yes, you got it...")
 7         break
 8     elif guess_age > age_of_oldboy:
 9         print("think smaller...")
10     else:
11         print("think bigger!")
12 else:
13     print("you have tried too many times...fuck off")

 输错n次时,退出

 1 age_of_oldboy = 56
 2 count = 0
 3 while count <3:
 4     guess_age = int(input("guess age:"))
 5     if guess_age == age_of_oldboy:
 6         print("yes, you got it...")
 7         break
 8     elif guess_age > age_of_oldboy:
 9         print("think smaller...")
10     else:
11         print("think bigger!")
12     count +=1
13     if count == 3:
14         countine_confirm = input("do you want to keep guessing...:")
15         if countine_confirm != 'n':
16             count = 0
执行结果:

guess age:45
think bigger!
guess age:123
think smaller...
guess age:123123
think smaller...
do you want to keep guessing...?5
guess age:123

二、break and continue

1 for i in range(5):
2     print('---------',i)
3     for j in range(5):
4         print(j)
5         if j >1:
6             break   #跳出整个循环,该例子是跳出for j in range(5)的循环
执行结果:

--------- 0
0
1
2
--------- 1
0
1
2
--------- 2
0
1
2
--------- 3
0
1
2
--------- 4
0
1
2

1 for i in range(5):
2     print('---------',i)
3     for j in range(5):
4         print(j)
5         if j >1:
6             continue  #continue是结束本次循环,即j=1时结束循环不再往下执行语句,直接跳到print(j)执行
执行结果:

--------- 0
0
1
2
3
4
--------- 1
0
1
2
3
4
--------- 2
0
1
2
3
4
--------- 3
0
1
2
3
4
--------- 4
0
1
2
3
4

 

 

posted on 2017-04-16 11:00  GXZZ685  阅读(130)  评论(0编辑  收藏  举报