首页 > 其他 > 详细

循环(while,for)

时间:2019-01-01 14:26:51      阅读:118      评论:0      收藏:0      [点我收藏+]

2019-01-01

一、while循环

标准格式如下:

count = 0
while True:
print("count:",count)
count = count +1 相当于count +=1

例子:
age_of_oldboy = ‘56‘
count = 0
while True :
if count == 3:
break
guss_age = input("guss the age:")
if guss_age == age_of_oldboy :
print("yes,you got it.")
break
elif guss_age > age_of_oldboy :
print("please guss smaller.")
else:
print("please guss bigger.")
count +=1
if count ==3
print("you have tried so many times ,you lose.")

可以精简代码如下:
count = 0
while count < 3:
guss_age = input("guss the age:")
if guss_age == age_of_oldboy :
print("yes,you got it.")
break
elif guss_age > age_of_oldboy :
print("please guss smaller.")
else:
print("please guss bigger.")
count +=1
else:
print("you have tried so many times ,you lose.")

二、for循环
标准格式如下:
‘‘‘
0,1,2,3,4,5,6,7,8,9
for i in range(10): 每循环一次取一个值
print("loop ",i)
‘‘‘
‘‘‘
0,3,6,9
for i in range(0,10,3): 每循环一次隔两个跳一个值(3-1)
print("loop ",i)
‘‘‘

例子:
age_of_oldboy = 56
for i in range(3):
guess_age = int(input("guess age:"))
if guess_age == age_of_oldboy:
print("yes,you got it.")
break
elif guess_age > age_of_oldboy:
print("please guess smaller.")
else:
print("please guess smaller.")
else:
print("you have tried too many times.you lose!")
三、while进阶
用户可以选择性循环
age_of_oldboy = 56
count = 0
while count < 3:
guss_age = input("guss the age:")
if guss_age == age_of_oldboy :
print("yes,you got it.")
break
elif guss_age > age_of_oldboy :
print("please guss smaller.")
else:
print("please guss bigger.")
count +=1
if count ==3:
countine_confirm = input("do you want to keep guessing...")
if countine_confirm != ‘n‘:
count = 0
#else:
# print("you have tried so many times ,you lose.")
四、循环套循环
for i in range(10):
print(‘--------‘,i)
for j in range(10):
print(j)
if j >2:
break
if i >2:
break
 

循环(while,for)

原文:https://www.cnblogs.com/study-notes-of-python/p/10204667.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!