def validate(s):
global Cap, Low, Num, Spec
''' Checks whether the string s fits the
criteria for a valid password.
'''
capital =['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lowercase = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
number = ['0','1','2','3','4','5','6','7','8','9']
special =['@','$','#']
for i in s:
if i in capital:
Cap = True
else:
Cap = False
if s in lowercase:
Low = True
else:
Low = False
if s in number:
Num = True
else:
Num = False
if s in special:
Spec = True
else:
Spec = False
if Cap and Low and Num and Spec is True:
return ('valid')
else:
return ('not valid')
def main():
''' The program driver. '''
# set cmd to anything except quit()
cmd = ''
# process the user commands
while cmd != 'quit':
cmd = input('> ')
password = cmd
validate(password)
main()
有人可以向我解释为什么我的节目没有返回“无效”'还是有效的?该程序应根据大写,小写,数字和特殊要求查看输入是有效密码还是无效密码。谢谢你的帮助。
答案 0 :(得分:1)
if ... else
放在函数内。False
循环之前将四个变量中的每一个初始化为for
。然后只有在满足条件时才将它们设置为True。if 'A' <= i <= 'Z'
之类的比较或使用str.islower()
,str.isupper()
和str.isdigit()
。对于特殊字符,您可以测试i
是否在字符串中。i
(而不是s
)elif
,因为这四个类别是互斥的。哪个给出了
def validate(s):
""" Checks whether the string s fits the
criteria for a valid password. Requires one of each
of the following: lowercase, uppercase, digit and special char
"""
special = '@$#'
Cap,Low,Num,Spec = False,False,False,False
for i in s:
if i.isupper():
Cap = True
elif i.islower():
Low = True
elif i.isdigit():
Num = True
elif i in special:
Spec = True
if Cap and Low and Num and Spec:
return 'valid'
else:
return 'not valid'
并验证(假设python3,对{python2使用raw_input
)
p = input("Password?")
print (validate(p))
答案 1 :(得分:-1)
你的程序不会返回任何东西,因为你没有打印任何东西。除非您输入quit
,否则您的同时会永远循环。
def main():
cmd = ''
while cmd != 'quit':
cmd = raw_input('> ')
isValid = validate(cmd)
print isValid
if isValid == 'valid':
return
如果您使用的是python&lt; 3.x使用raw_input
。如果$ python script.py
不起作用,请尝试$ python -i script.py
。
希望这有帮助。