【发布时间】:2020-08-26 22:01:54
【问题描述】:
我是 Python 新手,我正在尝试创建一个程序来使用 for 循环验证密码(我已经使用 while 循环编写了一个程序。但是它无法正常工作。
就像我说的,我对 Python 和代码编写非常陌生。我发现遍历字符串的值(输入密码)并解决如何处理异常(例如,不包含某些字符)特别困难。这是我编写的代码。
import string
import re
print('At least 1 letter between [a-z] and 1 letter between [A-Z]. \nAt least 1 number between [0-9]. \nAt least 1 character from [$#@]. \nMinimum length 6 characters. \nMaximum length 16 characters. \n')
def validate():
password = input('Enter your password: \n')
if (len(password) < 8):
print('Password must be at least 8 characters long')
elif (len(password) >= 16):
print('Password must be no more than 16 characteres long')
for i in password:
if (i.find(string.ascii_lowercase)):
print('At least one character must be in the range [a-z]')
elif (i.find(string.ascii_uppercase)):
print('At least one character must be in the range [A-Z]')
elif (i.find(string.digits)):
print('At least one character must be in range[0-9]')
elif (re.search('[@,#,$]', password) is None):
print('At least one of these characters (@ - # -$) must be included')
else:
print('your password is good:')
break
validate()
【问题讨论】:
-
这里for循环的目的是什么?我建议您真正考虑一下 if/else 逻辑的逻辑,因为它不起作用。当您在密码中为 i 执行操作时,您将密码中的每个字符迭代为 i。我强烈建议您绘制流程图并从那里开始工作。
-
基本上所有 4 个正则表达式都应该匹配...
[a-z]+ [A-Z]+ [0-9]+ [@#$]+
标签: python loops validation passwords