循环loop
有限循环 = 有次数的循环
无限循环 = 死循环
continue 结束本次循环,继续下次循环。
break 跳出当前整个循环
代码:
for循环例1
Python
# __author:"jiangmin"
# __date: 2019-06-04
_user = "jiamin"
_password = "1234"
#passed_authentcation = False
for i in range(3):
username = input("Name:")
password = input("password")
if username == _user and password == _password:
print("welcome %s login..."% _user)
# passed_authentcation = True
break #break 退出后跳出到for循环外面不执行else
else:
print("Invalid username or password !")
#if not passed_authentcation:
# print("你是猴子请来的吗?")
else: #for循环正常完成循环后执行else
print("你是猴子请来的吗?")
for循环列2
Python
a = [1,2,3,4,5,6]
for i in a:
print(i)
效果如下:
Python
1
2
3
4
5
6
while循环
Python
# __author:"jiamin"
# __date: 2019-06-04
_user = "jiangmin"
_password = "1234"
counter =0
while counter < 3: #当while后面的条件为真执行下面的代码
username = input("Name:")
password = input("password:")
if username == _user and password == _password:
print("welcome %s login..."% _user)
break #break 退出后跳出到for循环外面不执行else
else:
print("Invalid username or password !")
counter += 1
if counter == 3:
keep_going_choice = input("还想玩吗?【Y/N】")
if keep_going_choice == "y":
counter = 0
else: #for循环正常完成循环后执行else
print("你是猴子请来的吗?")
break与continue
Python
# __author:"jiangmin"
# __date: 2019-06-05
exit_flag = False
for i in range(10):
if i < 5:
continue #结束本次循环,继续下次循环
print(i)
for j in range(10):
print("layer2",j)
if j == 6:
exit_flag = True
break
if exit_flag == True:
break