python - 检查密码

标签 python python-3.x

我认为我有正确的想法来解决这个函数,但我不知道为什么 我没有得到文档字符串中显示的所需结果。谁能帮我解决这个问题吗?

def check_password(s):
'''(str, bool)
>>> check_password('TopSecret')
False
>>> check_password('TopSecret15')
True
'''
for char in s:
    if char.isdigit():
        if  char.islower():
            if char.isupper():
                return True
else:
    return False 

最佳答案

你的逻辑有缺陷,它应该是这样的:

def check_password(s):
    has_digit = False
    has_lower = False
    has_upper = False

    for char in s:
        if char.isdigit():
            has_digit = True
        if char.islower():
            has_lower = True        
        if char.isupper():  
            has_upper = True 

    # if all three are true return true
    if has_digit and has_upper and has_lower:
        return True
    else:
        return False

现在,让我们谈谈您的代码有什么问题。

def check_password(s):
    for char in s:
        if char.isdigit():
            if char.islower(): # we only get to this check if char was a digit
                if char.isupper(): # we only get here if char was a digit and lower
                    # it is not possible to get here
                    # char would have to be a digit, lower, and upper
                    return True
    else:
        return False

作为示例,让我们看一下 TopSecret15,我们从 T 开始

  1. isdigit = False,因此我们立即为“T”返回 false
  2. 我们将继续立即返回 false,直到达到“1”
  3. 假设我们在 1,isdigit 为 true,但 islower 为 false,因此它再次返回 false

你知道这三个对于同一个字符来说是如何不可能成立的吗?

您的代码相当于:

if char.isdigit and char.islower and char.isupper:
    # this will never happen

关于python - 检查密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47665631/

相关文章:

Python:什么时候应该使用子类而不是方法?

python - 如何为 python C++ 嵌入构建 boost 示例

python Selenium - 无法获取 Facebook 表格内容

Python:从列表列表中删除最后一个元素?

python - 将 map 与 queue.put() 一起使用?

python - SQLAlchemy 过滤不工作

python - 如何将 python 3.9.1 设​​为我在 MacOs 上的默认版本

python - rw+ 和 r+ 有什么区别

python - Pandas - 连接数据框

python - Windows 10 pip 安装 'Failed Connection'