首页 > 解决方案 > 为什么第 18 行的 if 语句不能防止错误“列表索引超出范围”

问题描述

我正在编写一个替换密码的程序,我很好奇为什么我在第 20 行得到列表索引超出范围,如果我将 0 传递到 x,如果它超过数组 key1 的 len

import string
import random


alphabet= 'abcdefghijklmnopqrstuvwxyz'
file1 = open("MyFile.txt","r")
dict1 = {}
key1 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,7]
key = 4
plain_txt= file1.read()
file1.close()
x = 0
cipher = []


for char in plain_txt:
    c = alphabet.find(char)
    if x > len(key1):
        x = 0
    c = c + key1[x]
    if c > 25:
       c = 0
    char  = alphabet[c]
    cipher.append(char)
    x +=1

cipher = "".join(cipher)
print(cipher)

标签: pythoncryptography

解决方案


推荐阅读