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

时间:2017-10-27 20:10:21

标签: python-3.x while-loop

我有一个遍历两个列表的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

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

1 个答案:

答案 0 :(得分:0)

当你抓住Except并用print打印它时,你不会告诉程序退出。您需要添加sys.exit()