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 callencode()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
encodecalls. Whenencode("p",16)runs, it matches the character, soplace_in_messageincrements from 0 to 1. - The remaining calls (from
encode("q",17)toencode("z",26)) still execute. At this point,place_in_messageis 1, but your message only has a length of 1 (valid index is 0), sodecoded_message[place_in_message]throws an index out-of-range error. - Worse, the
encodecalls that don't match the current character don't updateplace_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
alphabetarray starts at index 0 (alphabet[0] = "a"), but you passletterNumvalues 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_messageat the end, but your encoded string is stored inencoded_message—this would trigger aNameError. - Over-reliance on global variables: Your
encodefunction 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_charnow 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_messageconsistently 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
相关产品推荐
相关产品推荐

