密码代码运行报错:string index out of range,请求技术排查
Fixing the "string index out of range" Error in Your Caesar Cipher Code
Alright, let's break down exactly why you're hitting that IndexError and get your cipher working properly.
Root Cause of the Error
Your outer while n >= 0 loop condition is the main culprit. Let's walk through an example: say you input the word "DOG" (length 3, so n=3):
- First iteration:
n=3, you grabword[0](D), incrementito 1, decrementnto 2. - Second iteration:
n=2, grabword[1](O), incrementito 2, decrementnto 1. - Third iteration:
n=1, grabword[2](G), incrementito 3, decrementnto 0. - Fourth iteration:
n=0still satisfiesn >= 0, so you try to accessword[3]—but "DOG" only has indexes 0, 1, 2. That's the index out of range error!
On top of that, your inner loop never resets k to 0 after processing each letter. After the first letter, k stays at 26, so you'll never find a match for subsequent characters.
Fixed Code with Improvements
Here's a revised version that fixes the error and makes the logic cleaner and more robust:
def cipherText(): text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Handle invalid key input try: key = int(input("Enter numerical key--")) key = key % 26 # Ensure key stays within 0-25 to avoid unnecessary cycles except ValueError: print("Oops, please enter a valid whole number for the key.") return word = input("Type word to be ciphered--").upper() # Convert input to uppercase to match our text set n = len(word) i = 0 # Change loop condition to n > 0 to avoid the final out-of-bounds access while n > 0: letter = word[i] # Use text.index() to skip the inner loop and directly get the letter's position try: k = text.index(letter) except ValueError: print(f"Note: '{letter}' isn't an uppercase letter, skipping it.") i += 1 n -= 1 continue # Simplify the cipher index calculation with modulo (handles wrap-around automatically) cipher_length = (k + key) % 26 print(text[cipher_length], end="") # Keep ciphertext on one line i += 1 n -= 1 print() # Add a newline after the ciphertext cipherText() # Start the cipher function cipherText()
Key Changes Made:
- Fixed the loop condition: Changed
while n >=0towhile n >0—this stops the loop before we try to access an index that doesn't exist. - Removed redundant inner loop: Used
text.index(letter)to directly find the position of each letter, eliminating the need to resetkevery time and shortening the code. - Added input robustness:
- Converts the input word to uppercase so it matches the
textstring (no more failed matches for lowercase letters). - Validates that the key is an integer, and uses modulo 26 to ensure it's always within a useful range (even if someone enters a key like 30, it becomes 4).
- Handles non-alphabet characters gracefully instead of crashing.
- Converts the input word to uppercase so it matches the
- Cleaner output: Uses
end=""to print the ciphertext as a single string instead of one letter per line.
Example Test Run:
Enter numerical key--5 Type word to be ciphered--STACKOVERFLOW XYHFYPJWTAJQTD
内容的提问来源于stack exchange,提问作者Suraj Jha
相关产品推荐
相关产品推荐

