虽然循环在引发异常后仍在继续(Python 3)



>我有一个贯穿两个列表的 while 循环,当列表索引超出范围时,我希望它脱离 while 循环并结束。

cipher = string_toList(cipher)
plain  = string_toList(plain)
i = 0                     ## holds value for first two letter block                                             
j = 2                     ## holds value for next two letter block and is updated to find invertable matrix     
p1 = val(plain[i]); p2 = val(plain[i+1])
c1 = val(cipher[i]); c2 = val(cipher[i+1])
try:
    while True:
        p3 = val(plain[j]); p4 = val(plain[j+1])
        c3 = val(cipher[j]); c4 = val(cipher[j+1])
        b = [p1, p2, p3, p4]
        c = [c1, c2, c3, c4]
        det = det_matrix(b)
        if gcd(det, 26) == 1:
            break
        j += 2             ## incrimented by two in order to hold consistent blocks of letters                  
except:
    print ("plaintext input is not sufficient enough to find key matrix") 

return b,c,det

相反,该程序在 except 之后打印出消息,然后不会在终端上关闭并继续 while 循环。我不知道我做错了什么,任何帮助都非常感谢。

当你抓住Except,并使用print处理它时,你并没有告诉程序退出。 您需要添加sys.exit()

最新更新