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,它会说密码必须至少包含一个数字,它具有。 为什么这样,我该如何解决?
答案 0 :(得分:1)
正如评论所说,你正在检查每个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)
答案 1 :(得分:1)
不要做循环。转换密码以设置和检查交叉点,顺序如下:
digits = set("0123456789")
pw = set("password")
if not digits.intersection(pw):
# no digits in password