python中for循环(有限循环)和while循环(⽆限循环)
1. for循环
# for是有限循环,while是⽆限循环
# for后⾯也是可以接else
_user = "zgzeng"
_psw = "zgz"
# 限制登陆3次,如果3次登陆失败了,就会⾃动退出
for i in range(3):
username = input("Your name:")
password = input("Your password:")
if username == _user and password == _psw:
print("welcome to login our system")
else:
print("Invalid your username or password")
# 当登陆3次都失败了,优化给出提⽰再退出
# ⽅法1:使⽤标记
flag = False
for i in range(3):
username = input("Your name:")
password = input("Your password:")
if username == _user and password == _psw:
print("welcome to login our system")
# 当flag =True的时候,会执⾏后⾯if的代码
flag = True
break
else:
print("Invalid your username or password")
if not flag:
print("试了三次!")
# ⽅法2:除了if后⾯可以接else外,for后⾯也可以接
for i in range(3):
username = input("Your name:")
password = input("Your password:")
if username == _user and password == _psw:
print("welcome to login our system")
break
else:
print("Invalid your username or password")
else:
print("已经试了三次!")
# for循环后⾯可以接else,但不可以elif
# for循环程序执⾏,当程序正常执⾏完成,就会执⾏else,如果不正常执⾏,就不会执⾏else,这⾥3次以内登陆之后,就会break跳出程序,这⾥就是不正常执⾏,就不会执⾏else程序,⽽3次以内没能登陆成功,就会执⾏到else程序⽅法1和⽅法2的效果都是⼀样,但是明显⽅法2更加简洁
2.while循环
while循环如果不加条件,就是⼀个死循环
while也是可以接else,与for效果是⼀样的
counter = 0
while counter > 3:
username = input("Your name:")
password = input("Your password:")
if username == _user and password == _psw:
print("welcome to login our system")
# 当flag =True的时候,会执⾏后⾯if的代码
flag = True
break
else:
print("Invalid your username or password")
counter += 1
else:
print("已经试了三次")
# 程序优化每试3次,3次失败后,给出选择提⽰,是否继续尝试登陆
# 思路:每当循环试了3次之后,程序就会给出选择,那么我们就需要每尝试3次之后,就将counter清零
_user2 = "zgzeng"
_pwd = "zgzeng"
counter = 0
while counter < 3:
username = input("请输⼊⽤户名:")
password = input("请输⼊密码:")
if _user2 == username and password == _pwd:
print("欢迎登陆我的程序")
break
else:
print("您的⽤户名或者密码有误")
counter += 1
keep_going_choice = input("输⼊[y]将继续,其他退出")
if keep_going_choice == "y":
counter = 0
# 这⾥的执⾏效果是每执⾏1次,程序就会问是否继续,并没有实现我们理想中的效果(3次询问⼀次)
需要再加⼀个判断
_user2 = "zgzeng"while语句怎么用在python中
_pwd = "zgzeng"
counter = 0
while counter < 3:
username = input("请输⼊⽤户名:")
password = input("请输⼊密码:")
if _user2 == username and password == _pwd:
print("欢迎登陆我的程序")
break
else:
print("您的⽤户名或者密码有误")
counter += 1
if counter == 3: # 加⼀个判断
keep_going_choice = input("输⼊[y]将继续,其他退出")
if keep_going_choice == "y":
counter = 0
将循环和嵌套循环中的两次break进⾏关联也需要⽤到标记位flag = False
# ⽬标:嵌套层循环break,我外层循环因为内层循环跳出也跳出,否则不跳出# 知识点:标记位
for i in range(10):
if i > 5:
print(i)
for j in range(10):
print("第⼆层:",j)
if j == 6:
flag = True
break
if flag == True: # 这就将两个break关联起来了
break
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论