【问题标题】:Password checking program, for loop problems密码检查程序,用于循环问题
【发布时间】:2013-12-01 00:32:16
【问题描述】:

我正在开发一个 python 程序来检查文档中的一系列密码以查看它们是否有效。它们必须是 7 个字符长,至少包含 1 个大写字母、1 个小写字母、字母、1 个数字,并且不能包含其他字符。出于某种原因,我的 for 循环在仅检查第一个字符后终止,我无法弄清楚问题所在。有人可以看看我的代码并帮我解决这个问题吗?

def detectLength(word):
    if len(word) >= 7:
        return True
    else:
        return False

def detectSpecial(word):        
    if word.isalnum:
        return True
    else:
        return False

def detectCapital(word):
    for i in range(0, len(word)+1):
        if (ord(word[i]) >= 65 and ord(word[i]) <= 90):
            return True
        else:
            return False

def detectLower(word):
    for i in range(0, len(word)):
        if (ord(word[i]) >= 97 and ord(word[i]) <= 122):
            return True
        else:
            return False

def detectDigit(word):
    for i in word:
        if ord(i) >= 40 and ord(i) <= 57:
            return True
        else:
            return False

def main():
    print(format("Password Attempt", '20s'), format("Validity Result", '17s'), format("Reason", '15s'))
    print("======================================================")
    word = input()
    while word != "ZZZZ":
        if detectLength(word) == False:
            Validity, Reason = "Invalid", "Length"
        elif detectSpecial(word) == False:
            Validity, Reason = "Invalid", "Special Char"        
        elif detectCapital(word) == False:
            Validity, Reason = "Invalid", "No Uppercase"
        elif detectLower(word) == False:
            Validity, Reason = "Invalid", "No Lowercase"
        elif detectDigit(word) == False:
            Validity, Reason = "Invalid", "No Digits"
        else:
            Validity, Reason = "Valid", ""
        print(format(word, '20s'), format(Validity, '20s'), format(Reason, '14s'))
        word = input()
    print("======================================================")

main()

【问题讨论】:

  • 专业提示:比较测试已经返回TrueFalse;只返回比较结果。您还需要致电word.isalnum()。而不是if something == False:,请使用if not something:
  • 是的,需要调用 word.isalnum(),但现在它表示第一个字母之外的大写字母的密码尝试不是字母数字。

标签: python loops python-3.x passwords


【解决方案1】:

这是因为你如何构建你的 for 循环。在detectCapital中,如果第一个字符不是大写,则返回False。你应该返回True,如果它是大写的并且如果循环结束并且没有返回True,那么显然所有的字母都是小写的并且应该返回一个False。像这样:

def detectCapital(word):
    for i in range(0, len(word)+1):
        if (ord(word[i]) >= 65 and ord(word[i]) <= 90):
            return True
    return False

detectLowerdetectDigit 也有同样的问题。

【讨论】:

  • 谢谢!它工作得很好,我看到了我的错误!
猜你喜欢
  • 2015-07-06
  • 2022-01-05
  • 1970-01-01
  • 2020-02-29
  • 2017-01-08
  • 1970-01-01
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多