我大约 2 周前开始学习 python,并正在尝试创建一个可以存储多个用户名和密码的密码系统。我正在尝试添加一些代码,如果您输入错误密码 3 次,它会让您等待一分钟。
我不断收到错误消息,如果您输入密码错误 3 次并等待 60 秒,即使您输入了正确的密码和用户名,它也会打印“您的密码错误。您只剩下 3 次尝试了。”
有人可以帮助并指出我在代码中的缺陷吗?
import time
username = ["Test","Test2"]
password = ["1Ac!","2Bd!"]
success = 0
Tries = 0
Valid = False
Pass = ""
def login():
global success
global Pass
global Tries
inuser = input(str("Enter your username: \n"))
inpass = input(str("Enter your password: \n"))
if inuser not in username:
print("username not found in directory")
login()
else:
posUser = username.index(inuser)
Pass = password[posUser]
while success != 1:
if Tries == 3:
print("You have had too many attempts. Wait 60 seconds before trying again")
for i in range(60, 0, -1):
time.sleep(1)
print(i)
if Tries == 3:
Tries = 0
inuser=str("0")
inuser=str("0")
login()
else:
break
if Pass == inpass:
success=1
else:
Tries += 1
AttemptsLeft = (3 - Tries)+ 1
print("Your password is wrong. You have only {} attempts left.".format(AttemptsLeft))
login()
login()
if success==1:
print("Welcome to ------")
如果你摆脱递归,一切都会变得更简单。
import time
username = ["Test","Test2"]
password = ["1Ac!","2Bd!"]
success = 0
Tries = 0
Valid = False
Pass = ""
def login():
global success
global Pass
global Tries
while success != 1:
inuser = input(str("Enter your username: \n"))
inpass = input(str("Enter your password: \n"))
if inuser not in username:
print("username not found in directory")
else:
posUser = username.index(inuser)
Pass = password[posUser]
if Tries == 3:
print("You have had too many attempts. Wait 60 seconds before trying again")
for i in range(60, 0, -1):
time.sleep(1)
print(i)
Tries = 0
inuser=str("0")
inuser=str("0")
if Pass == inpass:
success=1
elif Pass != "":
Tries += 1
AttemptsLeft = (3 - Tries)+ 1
print("Your password is wrong. You have only {} attempts left.".format(AttemptsLeft))
login()
if success==1:
print("Welcome to ------")
您还应该考虑摆脱global
变量。相反,使用return
.
import time
username = ["Test","Test2"]
password = ["1Ac!","2Bd!"]
success = 0
Tries = 0
Valid = False
Pass = ""
def login():
success = 0
Pass = ""
Tries = 0
while success != 1:
inuser = input(str("Enter your username: \n"))
inpass = input(str("Enter your password: \n"))
if inuser not in username:
print("username not found in directory")
else:
posUser = username.index(inuser)
Pass = password[posUser]
if Tries == 3:
print("You have had too many attempts. Wait 60 seconds before trying again")
for i in range(10, 0, -1):
time.sleep(1)
print(i)
Tries = 0
inuser=str("0")
inuser=str("0")
if Pass == inpass:
return True
elif Pass != "":
Tries += 1
AttemptsLeft = (3 - Tries)+ 1
print("Your password is wrong. You have only {} attempts left.".format(AttemptsLeft))
if login():
print("Welcome to ------")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句