簡體   English   中英

python 3文件中的“列表索引超出范圍”錯誤

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

輸入“嘿哥們,你好嗎?”時,我有一個自制的文本加密腳本,該腳本輸出“列表索引超出范圍”錯誤。 作為要加密的文本,“ KFC”作為加密密鑰。

我得到的更准確:

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

我在此腳本中使用了兩個文件(主腳本和函數庫)。 我只是不知道此錯誤來自何處...這是我的主要腳本:

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)

這是我的函數庫文件:

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='')

謝謝已經!

我尚未對此進行測試,但是您似乎需要將大於號換為大於或等於,因為它可能會使1索引過高。

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

    currentscrtrank += 1 + scrtlst[scrtrankcounter]

例如,如果scrtlst的長度為5,則最高索引為4,因此,如果您嘗試使用scrtlst[5] ,則會出現錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM