You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.7 IndexError排查:自定义凯撒密码加密脚本报错

Hey there, let's break down what's causing that IndexError and fix up your script step by step!

1. The Root Cause of the IndexError

Your core issue lies in the loop logic:

  • You use for _ in range(amount_of_characters) to iterate over each character in your message, but inside each loop iteration, you call encode() 26 times (once for every letter in the alphabet).
  • For example, when testing with the message "p" (length 1), the loop runs once—but that single loop triggers 26 encode calls. When encode("p",16) runs, it matches the character, so place_in_message increments from 0 to 1.
  • The remaining calls (from encode("q",17) to encode("z",26)) still execute. At this point, place_in_message is 1, but your message only has a length of 1 (valid index is 0), so decoded_message[place_in_message] throws an index out-of-range error.
  • Worse, the encode calls that don't match the current character don't update place_in_message, so you end up re-checking the same index repeatedly until a match is found—then overshooting once it is.

2. Other Hidden Issues in Your Code

Beyond the index error, there are a few more problems that would break your encryption functionality:

  • Mismatched alphabet indexing: Your alphabet array starts at index 0 (alphabet[0] = "a"), but you pass letterNum values starting at 1 (e.g., "a" uses 1). This will shift your encryption to the wrong letters.
  • Incorrect key handling: When key + letterNum >=26, you subtract 26 from the key directly. This breaks future key calculations—you should instead use modulo 26 to wrap the index around the alphabet.
  • Variable name typo: You try to print encrypted_message at the end, but your encoded string is stored in encoded_message—this would trigger a NameError.
  • Over-reliance on global variables: Your encode function depends on multiple global variables, making the code hard to debug and maintain.

3. Fixed Version of Your Script

Here's a cleaned-up, working version of your code, with explanations of key changes below:

import array as arr

# Alphabet uses 0-based indexing (matches Python's list behavior)
alphabet = arr.array('u', ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"])

def encode_char(letter, current_key):
    # Get the correct index of the letter in the alphabet
    try:
        letter_index = alphabet.index(letter)
    except ValueError:
        # Return non-alphabet characters (like spaces/punctuation) as-is
        return letter, current_key
    
    # Calculate encoded index with modulo to wrap around the alphabet
    encoded_index = (letter_index + current_key) % 26
    # Update key for the next character
    new_key = current_key * 2
    return alphabet[encoded_index], new_key

# Get user input, convert message to lowercase for consistency
decoded_message = input("What's your message? ").lower()
initial_key = int(input("What's your key? "))

encoded_message = ""
active_key = initial_key

# Iterate directly over each character in the message
for char in decoded_message:
    encoded_char, active_key = encode_char(char, active_key)
    encoded_message += encoded_char

print("Encoded message:", encoded_message)

4. Key Changes Explained

  • Refactored encryption function: encode_char now takes inputs as parameters and returns outputs instead of relying on global variables, making logic easier to follow.
  • Simplified loop: We iterate directly over each character in the message, calling the encryption function once per character—no more redundant calls or index tracking.
  • Fixed indexing: Uses alphabet.index(letter) to get the correct 0-based index for each character.
  • Robust key handling: The modulo operator (% 26) ensures we never go out of bounds of the alphabet, even with large keys.
  • Non-alphabet support: The function returns non-letter characters unchanged, making the script work with spaces, punctuation, etc.
  • Typo fixed: Uses encoded_message consistently throughout the code.

Testing your example: input message "p" and key 16 will encode to "f" (15 + 16 = 31, 31 % 26 = 5, which maps to "f"), with no more index errors.

内容的提问来源于stack exchange,提问作者L Jen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:15:39