我正在使用密码检查程序来检查字符串是否是有效密码。我必须检查是否至少有八个字符,必须只包含字母和数字,最后两个字符必须是数字。
除了password.isdigit()
之外,这一切似乎都有效。有时密码有效,有时却没有。有什么建议吗?
# Gets the users password
password = input('Enter a string for password: ')
# Splices the last two characters of the password
lastTwo = password[-2:]
# Checks the password if it is less than 8 characters
while len(password) < 8:
print('The password you entered is too short.')
print()
password = input('Enter a string for password: ')
# Checks the password if it is composed of letters and numbers
while password.isalnum() == False:
print('Your password has special characters not allowed.')
print()
password = input('Enter a string for password: ')
# Checks the spice to verify they are digits
while lastTwo.isdigit() == False:
print('Your last two characters of your password must be digits.')
print()
password = input('Enter a string for password: ')
print('Your password is valid.')
答案 0 :(得分:2)
您提供的代码存在一些问题。特别是,您只需检查后续规则while len(password) < 8
。如果您给它一个长度为10的密码,则永远不会检查规则。此外,您不会在尝试每个新密码时更新lastTwo
解决此问题的一种方法是将整个while
语句中包含if...elif..elif...else...
的多个while
语句替换为:
# Gets the users password
password = input('Enter a string for password: ')
while True:
# Checks the password if it is less than 8 characters
if len(password) < 8:
print('The password you entered is too short.')
# Checks the password if it is composed of letters and numbers
elif not password.isalnum():
print('Your password has special characters not allowed.')
# Checks the spice to verify they are digits
elif not password[:-2].isdigit():
print('Your last two characters of your password must be digits.')
else:
# we only get here when all rules are True
break
print()
password = input('Enter a string for password: ')
print('Your password is valid.')
这应该按照您的意图运作。但是,虽然我们正在努力,为什么不告诉用户每个规则他们的密码已经破坏?从UI的角度来看,它有助于让用户了解情况。
如果我们存储信息消息以及是否符合相关规则,我们可以快速制定出已经破坏的所有规则,如下所示:
valid_password = False
while not valid_password:
# Get a password
password = input('\nEnter a string for password: ')
# applies all checks
checks = {
'- end in two digits': password[-2].isdigit(),
'- not contain any special characters': password.isalnum(),
'- be over 8 characters long': len(password) > 8
}
# if all values in the dictionary are true, the password is valid.
if all(checks.values()):
valid_password = True
# otherwise, return the rules violated
else:
print('This password is not valid. Passwords must:\n{}'.format(
'\n'.join([k for k, v in checks.items() if not v])))
print('Your password is valid.')
答案 1 :(得分:0)
您永远不会在while循环中更新lastTwo
的值。因此,想象一下用户是否首先输入了密码abc123
。然后,lastTwo
将计算为23
。
现在,您的代码会发现密码太短,并提示用户输入新密码。假设他进入abcdefgh
。现在通过了您的第一次和第二次检查。但请注意lastTwo
仍为23
,因此您的第三次检查将错误传递。
因此,每当您接受新密码或直接检查时,您应该重新计算lastTwo的值:
while (password[-2:]).isdigit() == False: