循环导致字符串索引超出范围错误 - 为什么?

时间:2017-11-19 22:39:03

标签: python

这部分代码用于学校项目,并将转换为伪代码,因此我只能使用python和伪代码共有的语法。此部分根据密码中使用的字符检查密码强度。

if (password_accepted == True) and (username_accepted == True):
    lowercase_array = ["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"]
    uppercase_array = ["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_array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
    security_level = 0
    lowercase_present = False
    uppercase_present = False
    number_present = False
    for i in range (0, len(password_to_be_checked)):
        for i in range (0, len(lowercase_array)):
            if password_to_be_checked[i] == lowercase_array[i]:
                lowercase_present = True
        for counter in range (0, len(uppercase_array)):
            if password_to_be_checked[i] == uppercase_array[i]:
                uppercase_present = True
        for i in range (0, len(number_array)):
            if password_to_be_checked[i] == number_array[i]:
                number_array = True

它在这一行给我错误:

  if password_to_be_checked[i] == lowercase_array[i]:
IndexError: string index out of range

1 个答案:

答案 0 :(得分:1)

您的错误来自

for i in range (0, len(number_array)):
    if password_to_be_checked[i] == number_array[i]:
         number_array = True

您的密码可能会比10更短i number_array

然后,您的代码会尝试访问密码中仅包含n个字符的字符n-1 - >的索引错误

替代解决方案:

def check(s):
    lowercase = "abcdefghijklmnopqrstuvwxyz" 
    # uppercase = lowercase.upper() # better then doing the adhoc upper() multiple times
    numbers = "0123456789"
    lowercase_present = False
    uppercase_present = False
    number_present = False
    for c in s:
        lowercase_present |= c in lowercase # same as += for + but for logical OR
        uppercase_present |= c in lowercase.upper() # adhoc ToUpper
        number_present |= c in numbers
        if lowercase_present and uppercase_present and number_present :
            break; # no need to test any further, got all 3
    print(s, " contains number: ", number_present, " lower: ", lowercase_present, "upper: ", uppercase_present)



check("lower")
check("lowerUpper")
check("lowerUpperNumber")
check("!!!")

Python可以做到这么好,而无需直接索引....

您甚至可以使用string.isnumeric()isalpha() - 您可以为执行此测试的伪代码创建自己的litte辅助函数