登录成功就break,登录不成功就打印
_user = "xiaoyanzi"_passwd = "woaini"pass_authentication = Falsefor i in range(3): username = input("username:") passwd = input("passwd:") if _user == username and _passwd == passwd: print("welcome to %s login"%username) pass_authentication = True break else: print("invalid username or passwd !!!")if not pass_authentication: print("不洗脚的小燕子!!!")
可精简为:
_user = "xiaoyanzi"_passwd = "woaini"for i in range(3): username = input("username:") passwd = input("passwd:") if _user == username and _passwd == passwd: print("welcome to %s login"%username) break else: print("invalid username or passwd !!!")else: print("不洗脚的小燕子!!!")
while循环(无限循环,又称死循环):
while true:print("中国人民万岁!")
输出结果为n个:
中国人民万岁!
_user = "xiaoyanzi"_passwd = "woaini"while true: #死循环 username = input("username:") passwd = input("passwd:") if _user == username and _passwd == passwd: print("welcome to %s login"%username) break else: print("invalid username or passwd !!!")else: print("不洗脚的小燕子!!!")
将死循环改为有限循环:
_user = "xiaoyanzi"_passwd = "woaini"counter = 0while counter < 3: username = input("username:") passwd = input("passwd:") if _user == username and _passwd == passwd: print("welcome to %s login"%username) break else: print("invalid username or passwd !!!") counter += 1else: print("不洗脚的小燕子!!!")
三次输入错误之后,是否还想继续3次,再继续3次,效果:
_user = "xiaoyanzi"_passwd = "woaini"counter = 0while counter < 3: username = input("username:") passwd = input("passwd:") if _user == username and _passwd == passwd: print("welcome to %s login"%username) True break else: print("invalid username or passwd !!!") counter += 1 if counter == 3: keep_going_choice = input ("还想玩么?[y/n]") if keep_going_choice == "y": counter = 0 else: print("不洗脚的小燕子!!!")