while True:
profilePassword = input("Password: ")
if profilePassword == "":
print("Your password can't be blank!")
continue
else:
pass
for n in profilePassword:
if n == " ":
print("Your password can't contain spaces!")
break
elif n not in "1234567890":
print("Your password has to contain at least one number!")
break
elif n not in "abcdefghijklmnopqrstuvwxyz":
print("Your password has to contain at least one lowercase letter!")
break
elif n not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
print("Your password has to contain at least one uppercase letter!")
break
else:
continue
所以我正在尝试创建一个程序来检查您的密码是否正确。出于某种原因,“不在”表现得不太好。例如,如果我写 asd123,它会说密码必须至少包含一个数字,它有。 为什么会这样?我该如何解决?
请您参考如下方法:
正如评论所说,您正在检查每个 char 是否为数字(如果是,则第二个 elif 失败,因为您检查它是否为字符)。这不是您想要做的,您只是想确保整个字符串包含一个数字。
您可以使用 regex为此:
if re.search(regex, password):
# regex found something
else:
# no match
我个人认为最好告诉用户所有失败的事情(而不是第一次失败)。
import re
def setPassword(profilePassword):
msg = ""
if re.search(r' ', profilePassword):
msg += "* Your password can't contain spaces!\n"
if not re.search(r'\d', profilePassword):
msg += "* Your password has to contain at least one number!\n"
if not re.search(r'[a-z]', profilePassword):
msg += "* Your password has to contain at least one lowercase letter!\n"
if not re.search(r'[A-Z]', profilePassword):
msg += "* Your password has to contain at least one uppercase letter!\n"
if msg == "":
print("Setting password was successfull")
else:
print("Setting password was not successfull due to following reasons:")
print(msg)
setPassword("")
setPassword(" ")
setPassword("a")
setPassword("A")
setPassword("1")
setPassword("asd123")
setPassword("aA1")
while True:
profilePassword = input("Password: ")
if profilePassword == "":
print("Your password can't be blank!")
continue
else:
pass
setPassword(profilePassword)
搜索时还发现了这个:Checking the strength of a password (how to check conditions)
