我正在尝试创建一个长度为6-10个字符的密码输入,如果密码错误则会出错
如果您输入错误密码3次,我会尝试制作错误消息并自动关闭。
E.G请输入密码:地狱(3个字符所以会重复) 请输入密码:helloa(6个字符无数字重复) 请输入密码:hell12(3个字符2个数字,所以你错了3次所以我希望它关闭)
错误:密码错误3次关闭.....
这就是我所做的
#Ask user for creation of password
iCount + 1 # Goes up by one everytime password is incorrect
for iCount in range (1,4):
while len(sPassword) <6 or len(sPassword) >10:
sPassword =input("Please enter a Password\n\t(Must be 6-10 Characters and must contain 2 numbers)\n Password: ")
if len(sPassword) >10:
print ("Error the password must be 6 characters or more 10 characters or less ")
if len([x for x in sPassword if x.isdigit()]) >= 2:
print (" Password is OK")
else:
print ("Error: The password must contain atleast 2 numbers")
elif iCount==3:
print ("error")
有人可以帮我吗?
答案 0 :(得分:1)
由于只允许三次猜测,您只需在代码中使用一个循环语句。如果你在for循环结束时运行,代码应该放弃。
def get_password():
for password_tries in range(3):
password = input("Enter your password: ")
if len(password) < 6:
print("Your password is too short (minimum of 6 characters).")
elif len(password) > 10:
print("Your password is too long (maximum of 10 characters).")
elif sum(c.isdigit() for c in password) < 2:
print("Your password does not contain enough digits (minimum 2).")
else: # none of the previous checks was hit, so password is valid!
return password
print("Too many failed password entries, giving up.")
return None # or maybe raise an exception here, instead
如果您真的不想要单独的功能,您可以使用变量来指示密码是否有效。这是上面最后几行的替代方案:
else: # none of the previous checks was hit, so password is valid!
password_is_valid = True
break # stop looping
else: # this else detects running off the end of the loop (break not called)
print("Too many failed password entries, giving up.")
password_is_valid = False
# user password and password_is_valid variables here