2014-11-09 81 views
0

我的代码正在运行,但定义什么使得强密码的第一行代码会导致代码的其余部分无效返回。例如,当第一行代码正在搜索一个数字字符时,其中的任何代码都会导致代码在满足要求时不打印消息。如果我从寻找一个数字,以寻找一个资本或小写字符改变它,那么任何编码以后也不会,如果代码需要寻找资金或小写等功能re.search密码检查错误

import re 
password = str(input("Please enter the password you wish to test the strength of.\n")) 
if re.search(r'[0-9]', password): 
    if re.search(r'[A-Z]', password): 
     if re.search(r'[a-z]', password): 
      print("Your password strength is STRONG.") 
elif re.search(r'[a-z]', password) and re.search(r'[A-Z]', password): 
    print("Your password strength is MEDIUM.") 
elif re.search(r'[0-9]', password) and re.search(r'[A-Z]', password): 
    print("Your password strength is MEDIUM.") 
elif re.search(r'[a-z]', password) and re.search(r'[0-9]', password): 
    print("Your password strength is MEDIUM.") 
elif re.search(r'[A-Z]', password) or re.search(r'[a-z]', password) or re.search(r'[0-9]', password): 
    print("Your password strength is WEAK.") 
+0

密码的长度是否会影响您在此处提供的强度等级? – shuttle87 2014-11-09 00:54:53

+0

如果密码在6到12个字符之间,那么只会测试强度。然而,长度并不影响力量,它只是它具有的字符。 – user3292752 2014-11-09 00:57:08

回答

0

,你就能把重构的东西这样

import re 
strength = 0 
password = str(input("Please enter the password you wish to test the strength of.\n")) 
if re.search(r'[0-9]', password): 
    strength += 1 
if re.search(r'[A-Z]', password): 
    strength += 1 
if re.search(r'[a-z]', password): 
    strength += 1 

if strength == 3 
    print("Your password strength is STRONG.") 

if strength == 2: 
    print("Your password strength is MEDIUM.") 

if strength == 1: 
    print("Your password strength is WEAK.") 

虽然,我相信有更好的做这件事的方式,尝试思考开箱:d

+0

如果我使用password.isupper或password.islower或password.isdigit,该方法是否可行? – user3292752 2014-11-09 00:59:03

+0

很可能不是,例如jez所说的“9gag”,会为所有这些方法返回False。太糟糕了没有hasupper,haslower或hasdigit方法 – 2014-11-09 01:04:10

1

按照通过使用密码“9GAG”的代码你自己的逻辑。在那里有[0-9]但是不是[A-Z]。口译员输入第一个if,因此被排除在随后的elifs之外,但它不会输入嵌套的if,并且处于陷阱状态。

这种方法可能会更容易:

hits = [ re.search(r'[0-9]', password) != None, re.search(r'[A-Z]', password) != None, re.search(r'[a-z]', password) != None ] 
strength = sum(hits) 
+0

现在这就是我所说的开箱即用的思想,bool在python上被当作一个int来处理,尽管对于刚刚学习的人来说它可能有点复杂。 – 2014-11-09 01:01:28

+0

是的。为了澄清,那么:每个术语're.search(pattern,passord)!= None'产生'真'(匹配)或'假'(不匹配)。在许多其他数值运算中,'sum'被视为1,'False'被视为0,所以例如sum([True,True,False])为2。 – jez 2014-11-09 01:05:50

0

我曾经试图执行一个更先进的密码强度算法(包括香农熵和的修改),但最终我看到了,这是一个难以解决的问题,并且当密码良好时不能真正说出。

你可能很容易确定的唯一的事情是密码非常糟糕。

所以,也许只是教育用户明智地选择密码或者在恰当的时候创建随机密码是最好的。

对密码施加任意规则通常是相当烦人的。例如。如果有人使用密码管理器生成随机密码,他们可能会违反规则,但仍然是好密码,因为它们是随机的。