简体   繁体   English

python 3文件中的“列表索引超出范围”错误

[英]“List index out of range” error in python 3 file

I have a homemade text encryption script which outputs a "List index out of range" error when I input "Hey dude, how are you doing?" 输入“嘿哥们,你好吗?”时,我有一个自制的文本加密脚本,该脚本输出“列表索引超出范围”错误。 as a text to encrypt and "KFC" as an encryption key. 作为要加密的文本,“ KFC”作为加密密钥。

I get this more precisely: 我得到的更准确:

Traceback (most recent call last): File "/Users/BCPianist/Google Drive/Project-Cryptonite/NCrypt.py", line 75, in <module> main(userIn, a) File "/Users/BCPianist/Google Drive/Project-Cryptonite/NCrypt.py", line 47, in main currentscrtrank += 1 + scrtlst[scrtrankcounter] IndexError: list index out of range

I have two files used in this script (the main script and a function library). 我在此脚本中使用了两个文件(主脚本和函数库)。 I just can't figure where this error is coming from... Here is my main script: 我只是不知道此错误来自何处...这是我的主要脚本:

import random
from cryptolib import *

# !/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
print("Content-Type: text/plain;charset=utf-8")  # Definit le code d'ecriture
print()  # Insere une ligne d'espacement.


def main(userin, numberedsecretkey):  # Fonction principale (le gros de l'encryption)
    """
   This is my main.
   >>> main("Allo", "Hey")
   10842839726
   """
    comments = True  # Definit si les commentaires lors de l'impression sont actif ou non (False les desactive)
    total = convdecimal(userin)  # Time to deal with the encryption key:

    scrtkeytotal = convdecimal(numberedsecretkey)

    # converting numbered message to list
    msglst = [int(elem) for elem in str(total)]
    if comments == True:
        printdebug("The initial numbered message is:%s " % msglst)
    # converting numbered key to list
    scrtlst = [int(thingy) for thingy in str(scrtkeytotal)]
    if not comments != True:
        printdebug("The initial  encryption key is:%s" % scrtlst)

    # Attempting Encryption

    scrtrankcounter = 0
    currentscrtrank = scrtlst[scrtrankcounter]

    while currentscrtrank < len(msglst):
        randomgen = random.randint(0, 9)
        msglst.insert(currentscrtrank, randomgen)
        if comments:
            printdebug(str(randomgen) + " was inserted at rank: " + str(
                scrtrankcounter) + ", therefore, at index position: " + str(currentscrtrank) + ".")
            printdebug("List now appears as: " + str(msglst))
        scrtrankcounter += 1
        if scrtrankcounter > len(scrtlst):
            scrtrankcounter = 0

        currentscrtrank += 1 + scrtlst[scrtrankcounter]

    return listtoint(msglst)


def convdecimal(userin):
    rank = len(userin)
    total = 0
    for character in userin:
        rank -= 1  # decreasing the letter rank by one

        letter = ord(character)
        if letter < 32:
            pass
        elif letter == 27:
            pass
        else:
            rankmult = 255 ** rank  # Making a multiplier
            lettervalue = letter * rankmult  # Multiplying the letter by this multiplier
            total += lettervalue  # Adding the letter's value to the total

    return total


if __name__ == "__main__":
    userIn = input("Enter the word/Sentence you want to encrypt:")
    a = input("Enter a password with which you would like to encrypt your message:")
    print(userIn)
    main(userIn, a)

And here is my function library file: 这是我的函数库文件:

import os

DEBUG = True


def printdebug(log: object) -> object:
    if DEBUG:
        print(log)


def loading(sec=10):
    start = 1
    input("Press Enter to continue")
    printdebug("loading...")
    while start <= sec:
        printdebug("...")
        start += 1


def codepause():
    os.system("Pause")
    input("press enter to continue")


def listtoint(msglst):
    # Conversion from list to int
    """
   >>> listtoint([1,2,3,4,5,6,7,8,9,0])
   1234567890
   """
    ncryptedkey = 0
    base = 10
    for d in msglst:
        ncryptedkey = base * ncryptedkey + d
    # printDebugJob:
    printdebug("The encrypted message is:" + str(ncryptedkey))
    return ncryptedkey


def convdecimal(userin):
    rank = len(userin)
    total = 0
    for character in userin:
        rank -= 1  # decreasing the letter rank by one

        letter = ord(character)
        if letter < 32:
            pass
        elif letter == 27:
            pass
        else:
            rankmult = 255 ** rank  # Making a multiplier
            lettervalue = letter * rankmult  # Multiplying the letter by this multiplier
            total += lettervalue  # Adding the letter's value to the total


def letterprint(nb):
    nb = chr(nb)

    print(nb, end='')

Thanks Already! 谢谢已经!

I've not tested this, but it looks like you need to swap the greater than sign for greater than or equals, as it's probably going 1 index too high. 我尚未对此进行测试,但是您似乎需要将大于号换为大于或等于,因为它可能会使1索引过高。

    if scrtrankcounter >= len(scrtlst):
        scrtrankcounter = 0

    currentscrtrank += 1 + scrtlst[scrtrankcounter]

For example, if scrtlst has a length of 5, the highest index is 4, so it'll give an error if you try scrtlst[5] . 例如,如果scrtlst的长度为5,则最高索引为4,因此,如果您尝试使用scrtlst[5] ,则会出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM