我正在尝试编写多个 if 语句来检查密码是否满足所有条件,而不是使用 if-elif 语句,它可以工作但一次只能验证一个条件。
我的代码似乎不起作用。当我输入包含字母和数字但太长/太短的密码时,代码的输出告诉我它太长/太短但也会触发“else”条件。然后代码不会循环返回。
谁能帮我理解这里的概念?非常感谢。
import re
while True :
password = input('Enter a password')
if not len(password) >= 6:
print('password too short')
if not len(password) <= 12:
print('password too long')
if not re.search(r'[a-z]', password):
print('password must contain at least a lowercase alphabet')
if not re.search(r'[0-9]', password):
print('password must contain at least a number')
else:
print('your password is fine')
break
请您参考如下方法:
你想写这样的东西
import re
while True :
ok = True
password = input('Enter a password')
if not len(password) >= 6:
print('password too short')
ok = False
if not len(password) <= 12:
print('password too long')
ok = False
if not re.search(r'[a-z]', password):
print('password must contain at least a lowercase alphabet')
ok = False
if not re.search(r'[0-9]', password):
print('password must contain at least a number')
ok = False
if ok:
print('your password is fine')
break
