循环(while,for)

Posted study-notes-of-python

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了循环(while,for)相关的知识,希望对你有一定的参考价值。

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)的主要内容,如果未能解决你的问题,请参考以下文章

Python 图中的while循环改for循环,怎么改,直接回答代码,谢谢

循环语句 while,do while ,for 循环

什么叫“写一个循环(for或者while)读入五个浮点数?”

DAY 04 while和for循环

第六篇:循环语句 - while和for

Python3练习题系列(03)