单独地说,这些陈述有效(我已经制作了个人帮助函数),并且我已将它们编译到一个函数上。我怎么能让他们一起工作?另外,如何在没有模块的情况下运行该程序'?它有效,但我从这个网站上的其他人那里得到了它。这些是我在这个计划中所需要的:
这是我的代码:
import re
def password_validator (pw_v, prev_p): #pw_v = string that is to be validated; prev_p = previously used strings in a list
prev_P = [s]
# do I use 'while True' instead of returning True statements every time?
if 10 <= len(s) <=20:
return True
elif s[0] and s[-1].isalpha():
return True
elif not re.search('(.)\\1{2}', s): # How else can I write this without using 're'?
return True
elif any(digit.isdigit() for digit in s):
return True
else:
return False
答案 0 :(得分:1)
将每个条件存储在一个变量中,例如has_correct_length和has_digit。
结合它们:
has_correct_length = (10 <= len(s) <=20)
has_digit = any(digit.isdigit() for digit in s)
fulfills_restrictions = has_correct_length and has_digit
通过这种方式,您的代码更易于阅读和记录。
答案 1 :(得分:1)
您的代码会检查输入是否只满足其中一个条件。
请注意,当您return
时,该函数返回并忽略其余代码。考虑到这一点,您可以使用:
(1)嵌套if
s
if 10 <= len(s) <= 20:
if s[0] and s[-1].isalpha():
# the rest of the conditions
return True # all of the conditions were met
return False # one of the conditions wasn’t met
(2)如果第一个条件未满足(实际使用De Morgan's laws),则返回false
。
if not 10 <= len(s) <= 20:
return False
if not s[0] and s[-1].isalpha():
return False
# the rest of the conditions
关于正则表达式的使用,在我看来它在这种情况下是优雅的;但是你总是可以切换到一个循环来迭代输入的字符,并结合重复字符的计数器(这不是优雅的):
def three_identical_characters(input):
counter = 0
for i in range(1, len(input)):
counter += (1 if (input[i] == input[i-1]) else 0)
if counter == 2:
return True
return False
答案 2 :(得分:-1)
您不测试是否满足条件,您测试是否满足条件:
import re
def password_validator (pw_v, prev_p): #pw_v = string that is to be validated; prev_p = previously used strings in a list
prev_P = [s]
# do I use 'while True' instead of returning True statements every time?
if not 10 <= len(s) <=20:
return False
elif not (s[0] and s[-1].isalpha()):
return False
elif re.search('(.)\\1{2}', s): # How else can I write this without using 're'?
return False
elif not any(digit.isdigit() for digit in s):
return False
else:
return True