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

密码代码运行报错: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):

  1. First iteration: n=3, you grab word[0] (D), increment i to 1, decrement n to 2.
  2. Second iteration: n=2, grab word[1] (O), increment i to 2, decrement n to 1.
  3. Third iteration: n=1, grab word[2] (G), increment i to 3, decrement n to 0.
  4. Fourth iteration: n=0 still satisfies n >= 0, so you try to access word[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 >=0 to while 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 reset k every time and shortening the code.
  • Added input robustness:
    • Converts the input word to uppercase so it matches the text string (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.
  • 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:23:03